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)
Show older comments
Michael Bochert
on 31 Jan 2024
Commented: Michael Bochert
on 31 Jan 2024
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.
0 Comments
Accepted Answer
Dyuman Joshi
on 31 Jan 2024
%Sample data for example
y1 = magic(5)
y2 = y1;
y2(randi(25,1,5)) = 0
%Comparison
idx = all(y1(:,1:2)==y2(:,1:2), 2)
out = y1(idx, :)
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
on 31 Jan 2024
In that case
%Sample data for example
y1 = magic(5)
y2 = [y1; randi(25, 2, 5)];
k = randi(numel(y2),1,14);
y2(k) = k*5
%Comparison
[idx1,idx2] = ismember(y1(:,1:2),y2(:,1:2),'rows')
out1 = y1(idx1, :)
out2 = y2(idx2(idx1),:)
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!