Trying to extract the rows from a matrix where the values from the first two columns match the values from another matrix

3 views (last 30 days)
Hi, I am trying to extract the rows from a matrix where the values from the first two columns of that matrix match the values from another matrix.
Basically, if the values in column 1 AND column 2 match the values for column 1 AND column 2 from another matrix, I want to extract the entire row. I want to do this for each row where the values match, essentially making a new matrix of the extracted rows.
Any help would be appreciated! Thanks.

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 31 Jan 2024
%Sample data for example
y1 = magic(5)
y1 = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
y2 = y1;
y2(randi(25,1,5)) = 0
y2 = 5×5
17 0 1 8 15 0 5 7 14 16 0 6 13 20 22 10 12 19 21 3 11 18 25 0 0
%Comparison
idx = all(y1(:,1:2)==y2(:,1:2), 2)
idx = 5×1 logical array
0 0 0 1 1
out = y1(idx, :)
out = 2×5
10 12 19 21 3 11 18 25 2 9
If you are working with floating point numbers, use a tolerance to compare instead of equality
tol = 1e-6;
idx = all(abs(y1(:,1:2)-y2(:,1:2))<tol,2)
  3 Comments
Dyuman Joshi
Dyuman Joshi on 31 Jan 2024
In that case
%Sample data for example
y1 = magic(5)
y1 = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
y2 = [y1; randi(25, 2, 5)];
k = randi(numel(y2),1,14);
y2(k) = k*5
y2 = 7×5
17 24 75 8 15 10 5 80 14 16 4 50 13 20 22 10 55 19 125 3 11 18 95 2 9 21 22 100 15 170 15 70 14 140 175
%Comparison
[idx1,idx2] = ismember(y1(:,1:2),y2(:,1:2),'rows')
idx1 = 5×1 logical array
1 0 0 0 1
idx2 = 5×1
1 0 0 0 5
out1 = y1(idx1, :)
out1 = 2×5
17 24 1 8 15 11 18 25 2 9
out2 = y2(idx2(idx1),:)
out2 = 2×5
17 24 75 8 15 11 18 95 2 9
For floating point numbers use ismembertol.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!