Trying to extract the rows from a matrix where the values from the first two columns match the values from another matrix
48 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Dyuman Joshi
2024-1-31
%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 个评论
Dyuman Joshi
2024-1-31
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),:)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!