Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Compare two vectors and got indices of the identical numbers
Replies: 4   Last Post: Feb 16, 2013 9:14 PM

 Messages: [ Previous | Next ]
 Nasser Abbasi Posts: 6,677 Registered: 2/7/05
Re: Compare two vectors and got indices of the identical numbers
Posted: Feb 16, 2013 9:02 PM

On 2/16/2013 7:48 PM, Nasser M. Abbasi wrote:
> On 2/16/2013 6:52 PM, Nasser M. Abbasi wrote:
>> On 2/16/2013 5:53 PM, Danny wrote:
>>> How to compare 2 vectors and got the indices of 2 identical numbers
>>>
>>> lets say I have matrix a

>>>>> a=[250;500;750;200;600;800;230;650;800]
>>>
>>> a =
>>>
>>> 250
>>> 500
>>> 750
>>> 200
>>> 600
>>> 800
>>> 230
>>> 650
>>> 800
>>>
>>> and I sort matrix a to matrix b
>>>

>>>>> b=sort(a)
>>>
>>> b =
>>>
>>> 200
>>> 230
>>> 250
>>> 500
>>> 600
>>> 650
>>> 750
>>> 800
>>> 800
>>>
>>> and I want to compare matrix b to matrix a to identify in which indices of matrix a is
>>> equal to the content of matrix b.
>>>
>>> For example for the number 230 in matrix b is located in the indices of #7 in matrix a
>>> or number 650 in matrix b is located in the indices of #8 in matrix a
>>>
>>> Thanks before for the answer
>>>
>>> Regards
>>>

>>
>> one way:
>>
>> -------------------------
>> a=[250;500;750;200;600;800;230;650;800];
>> b=sort(a,1);
>> N=length(a);
>> for i=1:N
>> [~,N(i)]=ismember(b(i),a);
>> end
>> N
>> --------------
>>
>> 4 7 1 2 5 8 3 9 9
>>

I was sleepy above. I meant to create a zero length array of length N
but ended up using N itself.

Ok, lets start over.

Now we'll find ALL locations in 'a' where 'b' value exist. Using
ismember only gives the largest index in 'a'. If that is ok
for you, then use ismember as in

[~,J]=ismember(b,a)

But to find all of them, then use find() instead of ismember.
But unless you want to use a cell, then you do not know the
size to preallocate for this. So using worst case, allocate
N by N matrix for the result (or use cell matrix).

----------------------
a=[250;500;750;200;600;800;230;650;800];
b=sort(a);
N=length(a);
M=zeros(N);
for i=1:N
z=find(b(i)==a);
M(i,1:length(z))=z;
end
M
-----------------------

4 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0 0
8 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0
6 9 0 0 0 0 0 0 0
6 9 0 0 0 0 0 0 0

For example, this ways the 8'th element in 'b' is found
in index 6 AND index 9 in 'a'.

If you like cell arrays, then use

M=arrayfun(@(i) find(b(i)==a),1:length(a),'UniformOutput',false)

--Nasser

Date Subject Author
2/16/13 Nasser Abbasi
2/16/13 Nasser Abbasi
2/16/13 Nasser Abbasi
2/16/13 dpb