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

19 ビュー (過去 30 日間)
Dave
Dave 2019 年 2 月 4 日
回答済み: Dilo 2022 年 10 月 30 日
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
%ANSWER SHOULD BE:
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 件のコメント
Guillaume
Guillaume 2019 年 2 月 4 日
Why isn't it
BBB = [601 %first element of B is 5, which is 3rd element of A, hence element (3, 1) of A2
602 %5 -> (3, 2)
101 %1 -> (2, 1)
102 %1 -> (2, 2)
103 %1 -> (2, 3)
501 %6 , 2nd element of A, hence (2, 1
]
Dave
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
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 件のコメント
Andrei Bobrov
Andrei Bobrov 2019 年 2 月 4 日
Yes, if B =[2 2 1 1 1 3]';
solution:
[~,~,c] = unique(B,'stable');
jj = cell2mat(arrayfun(@(x)(1:x)',accumarray(c,1),'un',0));
out = A2(sub2ind(size(A2),jj,B));
Dave
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));

サインインしてコメントする。

その他の回答 (2 件)

Dilo
Dilo 2022 年 10 月 30 日
1+2

Dilo
Dilo 2022 年 10 月 30 日
if true
% code
end

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by