38 views (last 30 days)

Hello all

I want to know...How can I get the indices of a value that is occuring only once in a vector...please guide.

Example: A=[1 1 0 -1 0 0 1 0 1 1]

Task: To identify the indices of -1 (as it is occuring only once) in A.

Please Help!!!

Regards

Cedric Wannaz
on 23 May 2014

Edited: Cedric Wannaz
on 23 May 2014

There are ways to solve your problem based on HISTC or ACCUMARRAY. However, the simplest approach if you really have only two situations (unique 1 or unique -1) is probably the following:

if sum( A == 1 ) == 1

pos = find( A == 1 ) ;

else

pos = find( A == -1 ) ;

end

value = A(pos) ;

Cedric Wannaz
on 23 May 2014

Note that you can contract this into a 2 liners

pos = find( A == (-1 + 2 * (sum(A==1) == 1)) ) ;

value = A(pos) ;

but you lose in clarity.

Cedric Wannaz
on 23 May 2014

Well, I would personally go for clarity .. otherwise there is even a one liner actually:

[~,pos,value] = find( A .* (A == -1 + 2*(sum(A==1)==1)) )

George Papazafeiropoulos
on 23 May 2014

Edited: George Papazafeiropoulos
on 23 May 2014

A=[1 1 0 -1 0 0 1 0 1 1];

[~,c]=histc(A,unique(A));

out=A(c==1);

Cedric Wannaz
on 23 May 2014

Mahdi
on 23 May 2014

If you're looking specifically for the value of -1, you can use the following:

index1=find(A==-1)

George Papazafeiropoulos
on 23 May 2014

Edited: George Papazafeiropoulos
on 23 May 2014

A=[1 1 -1 0 0 0 1 0 1 1];

[~,c]=histc(A,unique(A));

out=find(c==1);

George Papazafeiropoulos
on 23 May 2014

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

Start Hunting!
## 0 Comments

Sign in to comment.