Extract rows in a Matrix based on column values of another Matrix.
13 views (last 30 days)
Show older comments
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!
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/318697/image.png)
0 Comments
Accepted Answer
Stephen23
on 19 Jun 2020
Edited: Stephen23
on 19 Jun 2020
>> [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
More Answers (1)
David Hill
on 18 Jun 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
See Also
Categories
Find more on Matrices and Arrays 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!