Find common elements between two vectors and extract data from matrix (vectorized)

조회 수: 26(최근 30일)
Dave 2019년 2월 4일
댓글: Dave 2019년 2월 4일
Hello,
I understand this is different question than the one answered in
I need to find elements of one small vector into a big vector, and based on that generate a new vector (same size as big vector) using elements of a matrix.
%A is 4x1
A =[1, 6, 5'] %%elements are different
%B is much larger, 6x1
B =[5 5 1 1 1 6 ]'
%A2 is
A2=[101, 501, 601;
102, 502, 602;
103, 503, 603]
% BBB is same dim as B, but using elements from A2
BBB=[501 502 101 102 103 601]'
Using
[~,X]=ismember(B,A) %[~, ~, Xb]=unique(B) brings same result
Does not bring the correct location of columns in A2. Using
A=sort(A)
[~,X]=ismember(B,A)
does bring the correct location of columns in A2.
But how do I extract the rows?
댓글 수: 8표시숨기기 이전 댓글 수: 7
Dave 2019년 2월 4일
Hi, thanks. A2 is not transposed. Element (row,col) (3,1) in A2 is 103 and not 601.
You can take A as sorted, say As=sort(A)

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

채택된 답변

Andrei Bobrov 2019년 2월 4일
편집: Andrei Bobrov 2019년 2월 4일
A3 = fix(A2.*(10.^-floor(log10(A2))));
[ii,~] = find(squeeze(all(A3==reshape(B,1,1,[]))));
[~,~,c] = unique(ii,'stable');
jj = cell2mat(arrayfun(@(x)(1:x)',accumarray(c,1),'un',0));
out = A2(sub2ind(size(A2),jj,ii));
댓글 수: 4표시숨기기 이전 댓글 수: 3
Dave 2019년 2월 4일
Thanks a lot. Leaving the original B, I get ii
[~,ii] = ismember(B,sort(A))
and use the ii in
A2(sub2ind(size(A2),jj,ii));

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

Community Treasure Hunt

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

Start Hunting!