将Matlab代码C = B(:,ismember(B(1,:),A))转换为Python实现
Convert MATLAB's Column Extraction with
ismember to Python Got it, let's translate that MATLAB logic to Python using NumPy—since it's the closest equivalent for matrix operations like this. Here's how you can replicate the exact behavior:
Step-by-Step Breakdown
Your MATLAB code picks columns from matrix B where the first row's element exists in the row vector A. In Python, we'll use NumPy's isin() function to create a boolean mask, then index B with that mask to get the desired columns.
Example Code
import numpy as np # Define your input data (A can be a list or NumPy array) A = np.array([11, 12, 13, 14]) # 1D array works like MATLAB's row vector B = np.array([ [10, 11, 12, 15, 13], [20, 21, 22, 25, 23], [30, 31, 32, 35, 33] ]) # Extract columns where B's first row matches any element in A C = B[:, np.isin(B[0, :], A)] print(C)
Output
[[11 12 13] [21 22 23] [31 32 33]]
Key Details
np.isin(): This function checks each element inB[0, :](first row of B) against all elements inA, returning a boolean array whereTruemeans a match was found.- Column Indexing: The syntax
[:, mask]in NumPy is identical to MATLAB's(:, mask)for selecting columns—super intuitive if you're coming from MATLAB. - Flexibility: If
Ais a regular Python list instead of a NumPy array,np.isin()still works perfectly, no conversion needed. - Duplicates: Just like MATLAB, if
B's first row has duplicate elements present inA, all corresponding columns will be included inC.
内容的提问来源于stack exchange,提问作者Python1
相关产品推荐
相关产品推荐

