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

5 views (last 30 days)
Juan Pablo on 18 Jun 2020
Commented: Juan Pablo on 21 Jun 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.

Stephen Cobeldick on 19 Jun 2020
Edited: Stephen Cobeldick on 19 Jun 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
Juan Pablo on 21 Jun 2020
Thanks for your help! I was trying with ismember but not in the right way.

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
Juan Pablo on 19 Jun 2020
The dimesions of the matrix q and p are not the same. I could not use your approach.

R2019b

### Community Treasure Hunt

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

Start Hunting!