Extract rows in a Matrix based on column values of another Matrix.

23 vues (au cours des 30 derniers jours)
Juan Pablo
Juan Pablo le 18 Juin 2020
Commenté : Juan Pablo le 21 Juin 2020
I want to ask for help with constructing a matrix based on the values of another matrix.
I should to take the values of the matrix q based on the values in matrix p. I want to keep the same order or matrix p, but not successfully extracting the values in q. I should look for the value in the first column in q and then take all the values of that row.
I was using q(p), but this takes the values of p as the location in q, and when to try to extract them, it did not work as I do not have so many values in q. I could not find another similar example in the post, so ask you guys if one of you can help me.
Thanks for your help!

Réponse acceptée

Stephen23
Stephen23 le 19 Juin 2020
Modifié(e) : Stephen23 le 19 Juin 2020
The standard MATLAB approach to this common task is to use the second output of ismember, e.g.:
>> [X,Y] = ismember(p,q(:,1));
>> out = q(Y(X),:)
which returns a 177550x5 output matrix:
out =
181159 8 18 19 7
181160 29 56 57 27
181171 18 54 44 19
181172 56 145 120 57
181183 54 178 124 44
181184 145 347 285 120
181195 178 400 401 124
181196 347 649 660 285
181207 400 583 577 401
181208 649 877 882 660
181219 583 652 460 577
... lots more rows here
277980 83878 82141 85350 85440
277981 91191 88183 91390 92407
277992 82141 83366 85108 85350
277993 88183 89522 90415 91390
278004 83366 84276 84891 85108
278005 89522 90423 89846 90415
Note that you can also confirm that all p values were matched:
>> all(X)
ans =
1
  1 commentaire
Juan Pablo
Juan Pablo le 21 Juin 2020
Thanks for your help! I was trying with ismember but not in the right way.

Connectez-vous pour commenter.

Plus de réponses (1)

David Hill
David Hill le 18 Juin 2020
count=1;
for k=p
a=find(q(:,1)==k);%assume there is only one match
if ~isempty(a)
newMatrix(count,:)=q(a,:);
count=count+1;
end
end
  1 commentaire
Juan Pablo
Juan Pablo le 19 Juin 2020
The dimesions of the matrix q and p are not the same. I could not use your approach.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by