如何在MATLAB中查找数组中包含特定元素的行号?
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 istrueif the corresponding row inaexactly matchestarget, andfalseotherwise.find()converts that logical array into the actual row index (here, it will return4).
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 inato the corresponding element intarget(MATLAB automatically broadcasts the 1x2targetto match the 5x2 size ofa).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 - targetsubtracts the target from each row (thanks to MATLAB's broadcasting).abs()ensures we're only dealing with non-negative differences, andsum(..., 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

