Trying to extract the rows from a matrix where the values from the first two columns match the values from another matrix
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Michael Bochert
le 31 Jan 2024
Commenté : Michael Bochert
le 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 commentaires
Réponse acceptée
Dyuman Joshi
le 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 commentaires
Dyuman Joshi
le 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),:)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!