如何提取矩阵中第一列值为指定数的行?附实操示例
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 ofA== 1generates a boolean array ([true; false; true; false]in this case) that marks which rows meet the conditionA(row_mask, :)selects all columns (:) for the rows whererow_maskistrue—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

