简体   繁体   中英

matlab find specific VALUES in an array

How to find out all array element indices equal to several values (>2)

For example, I have an array a= [1 2 3 4 5 5 4 3 2 2 2 1] , I want to know the indices of all elements equal to b= [2 5]

Remember, I cannot use style like a==b(1) | a==b(2) a==b(1) | a==b(2) because number of elements in b is arbitrary.

Do I have to use a for loop to do this?

You can use ismember (as Daniel said just seconds before I hit enter...) ;-)

a=[1 2 3 4 5 5 4 3 2 2 2 1];
b=[2 5];
c=find(ismember(a,b))

Output:

c =

    2    5    6    9   10   11

如果您想手动进行操作,可以使用bsxfun

c = find(any(bsxfun(@eq, a(:).', b(:)), 1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM