You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取矩阵中第一列值为指定数的行?附实操示例

Extract Rows Where First Column Equals a Specific Value

Hey there! Let's break down how to solve this problem—extracting rows from matrix A where the first column has a value of 1 to form matrix B. I'll cover solutions for the most common tools you might be using:

Matlab/Octave

This matches the syntax of your example matrix. The approach uses logical indexing to target the right rows:

% Define your original matrix
A = [1 2 3; 3 4 5; 1 6 7; 2 2 1];

% Create a logical index where the first column equals 1
row_mask = A(:, 1) == 1;

% Use the mask to extract the desired rows
B = A(row_mask, :);
  • A(:, 1) grabs the entire first column of A
  • == 1 generates a boolean array ([true; false; true; false] in this case) that marks which rows meet the condition
  • A(row_mask, :) selects all columns (:) for the rows where row_mask is true—exactly the rows you want!

Python (with NumPy)

If you're working with numerical matrices in Python, NumPy makes this straightforward:

import numpy as np

# Define the matrix as a NumPy array
A = np.array([[1, 2, 3], [3, 4, 5], [1, 6, 7], [2, 2, 1]])

# Filter rows where the first column (index 0) is 1
B = A[A[:, 0] == 1, :]

The logic mirrors Matlab: A[:, 0] gets the first column, ==1 creates the boolean mask, and applying that mask to the array pulls out the matching rows.

Pure Python (No Libraries)

If you're working with a regular list of lists (no NumPy), a list comprehension does the trick cleanly:

# Define the matrix as a list of lists
A = [[1, 2, 3], [3, 4, 5], [1, 6, 7], [2, 2, 1]]

# Filter rows where the first element (index 0) is 1
B = [row for row in A if row[0] == 1]

This iterates over each row in A and keeps only those where the first element equals 1.

Key Takeaway

Across all tools, the core idea is the same: identify which rows have the target value in the first column, then extract those rows. The syntax varies slightly, but the logic stays consistent.

内容的提问来源于stack exchange,提问作者mahdi luis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:27:09