Find elements of an array in another array

70 ビュー (過去 30 日間)
Alexandru
Alexandru 2013 年 9 月 20 日
Hello,
Let's say I have 2 arrays of double, call then A and B. If both have unique entries and I want to find the position of each element of A in array B I can do:
[~, pos] = ismember(A,B);
What if the elements of A show up multiple times in B and I want to get the first time they show up or the last time they show up? I know I can do
pos = zeros(length(A),1);
for k = 1:length(A)
pos(k) = find(B == A(k),1,'first');
end;
But is there a better, more efficient way of doing it? For loops are not exactly in the spirit of Matlab as far as I know.
Thanks, Alex
  1 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 20 日
If
a=[1 2 3 4 5 6 7]
b=[12 13 2 4 3 2 4 2 25]
what is the expected result?

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

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 20 日
編集済み: Azzi Abdelmalek 2013 年 9 月 20 日
Maybe in your case, all element in A are present in B
A=[1 2 3 4 5 6 7]
B=[12 13 2 4 3 2 4 2 25 1 6 7 5]
pos=arrayfun(@(x) find(B==x,1),A)
  2 件のコメント
Alexandru
Alexandru 2013 年 9 月 20 日
Thanks Azzi! If I do find(B==x,1,'first') or find(B==x,1,'last') in your code I get exactly what I want.
One more question. Suppose I want to get the second occurrence when it exists. So for the second element of A which is 2 the positions it shows in B are 3, 6 and 8. Suppose I want the code to return 6. How would I modify it?
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 20 日
編集済み: Azzi Abdelmalek 2013 年 9 月 20 日
Use in the loop
id=find(B==A(k),2)
id=id(2)

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 20 日
編集済み: Azzi Abdelmalek 2013 年 9 月 20 日
I prefer this one. It should be much faster
A=[1 2 3 4 5 6 7]
B=[12 13 2 4 3 2 4 2 25 1 6 7 5];
[ii,jj]=unique(B,'stable');
n=numel(A);
pos = zeros(n,1);
for k = 1:n
pos(k)=jj(find(ii == A(k)));
end;
  2 件のコメント
Alexandru
Alexandru 2013 年 9 月 20 日
Ok, so in this case it would come down to a for loop.
Thanks again!
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 20 日
編集済み: Azzi Abdelmalek 2013 年 9 月 20 日
This answer is more efficient then the first one

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by