Spacey
Spacey

Reputation: 3019

Find specific occurrences within a vector in MATLAB, without for-loop?

I have a problem that seems to be simple but maybe I am missing something. Let us say I have: vector = [10:1:19];. I have another vector, want = [11 16 19]; I simply want a way in which a command will return for me, the indicies at which 11, 16, and 19 occur in vector. In other words, I want to have returned, 2, 7, and 10. What command might do this? I cannot use find, (because dimensions do not match), so is there another way?

In reality the length of vector and want will be long, so a for loop will not do.

Upvotes: 3

Views: 165

Answers (2)

Oli
Oli

Reputation: 16035

Alternatively, you can use ismember.

To get the element of vector present in want:

vector(ismember(vector,want))
ans =
     11     16    19

To get their indexes:

find(ismember(vector,want))
ans =
     2     7    10

or just:

[tf, loc] = ismember(vector,want)
tf =
     0     1     0     0     0     0     1     0     0     1
loc =
     0     1     0     0     0     0     2     0     0     3

where tf indicates for each element of vector whether it is present in want, and loc indicate the corresponding indexes in want.

Upvotes: 1

p8me
p8me

Reputation: 1860

Use intersect:

[C, i_vector, i_want] = intersect(vector, want)

C is the common elements in both vectors. i_vector would be the common set indices in vector and i_want is the matching set indices in want vector.

Upvotes: 7

Related Questions