How do I select rows with matching values for certain columns from two differently sized arrays?
6 views (last 30 days)
Show older comments
I have two arrays (M1 and M2) of common length but different height, where the first three columns contain indices I would eventually like to match between the arrays. I would like to make a new array with only the rows where the values of the first three columns of M2 equal the values of the first three columns for some row in M1. Here is my current strategy:
M2_trimmed = M2(any((M2(:,1:3)==(M1(:,1:3))),2),:);
However, I get the error "Arrays have incompatible sizes for this operation", presumably because I am unable to use the "==" operator between arrays of different size. Any suggestions on how else I might accomplish this?
0 Comments
Answers (1)
Image Analyst
on 12 Nov 2021
Try this:
% Sample data
M1 = [1,2,3,4
4,5,6,7]
M2 = [1,2,3,4;5,3,2,7;5,6,7,9]
[rows1, columns1] = size(M1)
[rows2, columns2] = size(M2)
% Find the number of rows in the tallest matrix.
maxRows = max(rows1, rows2)
% Expand arrays so both are the same height.
if rows1 < maxRows
M1(maxRows, end) = 0
end
if rows1 < maxRows
M2(maxRows, end) = 0
end
% Find rows where columns 1-3 of M1 match columns 1-3 of M2.
matchingRows = all(M2(:, 1 : 3) == M1(:, 1 : 3), 2)
M2_trimmed = M2(matchingRows,:)
5 Comments
Image Analyst
on 12 Nov 2021
So let's clarify. Do you want to keep the row in M2 is those first 3 column numbers occur anywhere in M1 (i.e. not necessarily the very same row number, but anywhere at all)? If so use ismember().
And conversely, you want to keep the row in M1 is those first 3 column numbers occur anywhere in M2 (i.e. not necessarily the very same row number, but anywhere at all)? If so use ismember().
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!