Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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. Thank you.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

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.

share|improve this answer
1  
Thank you! I had NO clue about this. How does MATLAB make this command run extremely fast btw? What is occurring under the hood? Surely no for loops right? –  Learnaholic Jun 12 '13 at 22:47
1  
@Learnaholic well structured for loops can be pretty fast. Also MatLab is just optimized for matrices. –  KronoS Jun 12 '13 at 22:49
    
@Learnaholic: Also many Matlab built-in functions are optimized and pre-compiled, and if I am not mistaken this sometimes results in more speed. –  pm89 Jun 12 '13 at 22:53
    
@pm89, yes, although I am wondering how one can possibly optimize a for-loop even if pre-compiled... –  Learnaholic Jun 12 '13 at 23:00
1  
+1 for a nice answer using a function I hadn't even heard of :) –  David_G Jun 12 '13 at 23:45

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.