How does the command unique work?

66 Ansichten (letzte 30 Tage)
ubaid haroon
ubaid haroon am 2 Mär. 2017
Beantwortet: John BG am 2 Mär. 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 Kommentar
Stephen23
Stephen23 am 2 Mär. 2017
Bearbeitet: Stephen23 am 2 Mär. 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

John BG
John BG am 2 Mär. 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

Weitere Antworten (0)

Kategorien

Mehr zu Dates and Time finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by