I have an array a = [1 5 2 5 3 5 4 5]. I have a second array b = [2,3,4].
I want to type something like c = find(a == b), but Matlab doesn't like it that the dimensions don't agree. The answer I am looking for is c = [3,5,7].
I know I could do it with a for loop. Trying to avoid a for loop for speed concerns. Any help would be appreciated.

 採用された回答

Image Analyst
Image Analyst 2012 年 3 月 20 日

31 投票

Use ismember:
a = [1 5 2 5 3 5 4 5]
b = [2,3,4]
% Give "true" if the element in "a" is a member of "b".
c = ismember(a, b)
% Extract the elements of a at those indexes.
indexes = find(c)
Results:
a =
1 5 2 5 3 5 4 5
b =
2 3 4
c =
0 0 1 0 1 0 1 0
indexes =
3 5 7
Obviously you can do away with "c" if you want, and just have a one-liner. I did it in two steps just for tutorial purposes.

5 件のコメント

Edward Umpfenbach
Edward Umpfenbach 2012 年 3 月 20 日
Perfect. Thanks.
Yu
Yu 2014 年 6 月 12 日
what if the number in a is unique, e.g a=[1,2,3,4,5,6,7,8,9], and b=[2,3,3] then, i would like to know the location of the numbers of b in a, according to you algorithm, the result will be [2,3], but i actuall would like to have the result of [2,3,3], since there are two 3 in b.
Any suggestion?
In your example, if 5 is included in b, the result is unacceptable as well. the ans will be : 2 3 4 5 6 7 8
hwo to improve?
Supraj Akileti
Supraj Akileti 2016 年 5 月 4 日
I have a follow up on this. What if the number is a = [1 5 2 5 3 5 4 2 5] and b = [5,2,4]. Acc to the above algorithm the index would be [2 3 4 6 7 8 9] but I actually would like to have the result [2,4,6,9,3,8,7]. Any suggestions?
Image Analyst
Image Analyst 2016 年 5 月 5 日
Supraj:
Try this:
a = [1 5 2 5 3 5 4 2 5]
b = [5,2,4]
output = [];
for k = 1 : length(b)
output = [output, find(a == b(k))]
end
Shlomo Geva
Shlomo Geva 2020 年 12 月 2 日
編集済み: Shlomo Geva 2020 年 12 月 2 日
Without an explicit loop (a bit convoluted, sorry, just having fun, 8 years too late)
a = [1 5 2 5 3 5 4 2 5];
b = [5,2,4];
[~,Locb]=ismember(a,b);
[s,si]=sort(Locb);
out=si(s>0)
out =
2 4 6 9 3 8 7
>>

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

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2014 年 6 月 12 日

12 投票

Use the second output of ismember:
a = [4 3 1 2 5]
b = [2 3 3]
[tf, loc] = ismember(b,a)
% loc is [ 4 2 2] as required
Shlomo Geva
Shlomo Geva 2020 年 12 月 2 日
編集済み: Shlomo Geva 2020 年 12 月 2 日

0 投票

function out = findMultipleElements(a,b)
% Find multiple elements in an array
% example:
% a = [1 5 2 5 3 5 4 2 5]
% b = [5,2,4]
% result = [2,4,6,9,3,8,7] % the indexes in a of elements from b, in order
% % The convoluted (obfuscated) solution.
[~,Locb]=ismember(a,b);
[s,si]=sort(Locb);
out=si(s>0);
% % The straight shooter solution.
% out = [];
% for n = 1:length(b)
% out = [out,find(a==b(n))]
% end
end

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by