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

如何在MATLAB中查找数组中包含特定元素的行号?

Find Row Index of a Specific Row in MATLAB Array

Hey there! Let's walk through how to find the row number containing [7 8] in your array a = [1 2; 3 4; 5 6; 7 8; 9 10];. There are a few straightforward, readable ways to do this in MATLAB—pick the one that fits your workflow best:

Method 1: Using ismember with Row Matching

This is the most intuitive approach, as it directly checks for full row matches:

a = [1 2; 3 4; 5 6; 7 8; 9 10];
target = [7 8];
row_number = find(ismember(a, target, 'rows'));
  • ismember(a, target, 'rows') returns a logical array where each entry is true if the corresponding row in a exactly matches target, and false otherwise.
  • find() converts that logical array into the actual row index (here, it will return 4).

Method 2: Explicit Element-wise Check with all()

If you want to break down the comparison step, use element-wise equality checks combined with all() to verify the entire row matches:

a = [1 2; 3 4; 5 6; 7 8; 9 10];
target = [7 8];
row_number = find(all(eq(a, target), 2));
  • eq(a, target) compares every element in a to the corresponding element in target (MATLAB automatically broadcasts the 1x2 target to match the 5x2 size of a).
  • all(..., 2) checks if all elements in each row are equal (meaning the entire row is a match).
  • find() pulls out the index of the matching row.

Method 3: Sum of Absolute Differences

Another way to confirm exact matches is to calculate the sum of absolute differences between each row and the target—if the sum is 0, the rows are identical:

a = [1 2; 3 4; 5 6; 7 8; 9 10];
target = [7 8];
row_number = find(sum(abs(a - target), 2) == 0);
  • a - target subtracts the target from each row (thanks to MATLAB's broadcasting).
  • abs() ensures we're only dealing with non-negative differences, and sum(..., 2) adds these values up row by row.
  • Rows with a sum of 0 are perfect matches, so find() returns their indices.

Quick Note on Duplicates

If your array has multiple rows matching target, all three methods will return all matching row indices (for example, if a had two rows of [7 8], row_number would be a vector like [4; 6]).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:02:21