MATLAB Answers

How does the command unique work?

20 views (last 30 days)
ubaid haroon
ubaid haroon on 2 Mar 2017
Answered: John BG on 2 Mar 2017
Hello,
Someone at my work told me to use unique to get some values out of the array. The array is stored with values [2 3 10 11 12 13 15 17....990]. someone values between 2:990 are missing. No value is repeated, but the unique(array) produces the result [ 2 3 4 5 6 7 8 9 10] which is what I want. Can someone explain me why? I thought that unique outputted sorted unique values of that array.

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 2 Mar 2017
@ubaid haroon: can you please show us the exact input values that you use, and how you call this function. unique works as expected for me, using the sample values that you gave:
>> unique([2,3,10,11,12,13,15,17,990])
ans =
2 3 10 11 12 13 15 17 990

Sign in to comment.

Accepted Answer

John BG
John BG on 2 Mar 2017
Hi Haroon
it does return the unique values sorted out, but what perhaps confuses you is the amount of output arguments you are using:
1.
unique returns up to 3 values
A=[4 4 3 -1 -1 10 10]
[L,ni,nj]=unique([4 4 3 -1 -1 10 10])
L =
-1 3 4 10
ni =
4
3
1
6
nj =
3
3
2
1
1
4
4
where A(ni) and L are the same
A(ni)
=
-1 3 4 10
isequal(L,A(ni))
=
1
and L(nj)=A
sequal(L(nj),A)
=
1
2. if you only take 2 outputs, only the positions of the 1st found unique values are returned, along with the unique values
[L,ni]=unique([4 4 3 -1 -1 10 10])
L =
-1 3 4 10
ni =
4
3
1
6
3. with only one output variable, there are not indices, just the 1st-found unique values
unique([4 4 3 -1 -1 10 10])
=
-1 3 4 10
so the progressive numerals you mention are actually the indices of the unique values found, since there are no repeated values, you see the progressive indices as found along th vector.
Check the output variables of the unique you are using and make sure values and indices are not crossed.
if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help solving your question,
please click on the thumbs-up vote link,
thanks in advance
John BG

  0 Comments

Sign in to comment.

More Answers (0)

Sign in to answer this question.