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

조회 수: 20 (최근 30일)
Juan Pablo
Juan Pablo 2020년 6월 18일
댓글: Juan Pablo 2020년 6월 21일
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!

채택된 답변

Stephen23
Stephen23 2020년 6월 19일
편집: Stephen23 2020년 6월 19일
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
Juan Pablo
Juan Pablo 2020년 6월 21일
Thanks for your help! I was trying with ismember but not in the right way.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

David Hill
David Hill 2020년 6월 18일
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
Juan Pablo
Juan Pablo 2020년 6월 19일
The dimesions of the matrix q and p are not the same. I could not use your approach.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by