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

将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 in B[0, :] (first row of B) against all elements in A, returning a boolean array where True means 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 A is 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 in A, all corresponding columns will be included in C.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:32:58