What makes MATLAB unique? You have your choice regarding which element unique returns when there are repeated values in an array. What I wonder about is why it matters.
If you look at the help for unique
helptext = help('unique'); helptext = helptext(1:650)
helptext = UNIQUE Set unique. B = UNIQUE(A) for the array A returns the same values as in A but with no repetitions. B will also be sorted. A can be a cell array of strings. UNIQUE(A,'rows') for the matrix A returns the unique rows of A. [B,I,J] = UNIQUE(...) also returns index vectors I and J such that B = A(I) and A = B(J) (or B = A(I,:) and A = B(J,:)). [B,I,J] = UNIQUE(...,'first') returns the vector I to index the first occurrence of each unique value in A. UNIQUE(...,'last'), the default, returns the vector I to index the last occurrence. See also UNION, INTERSECT, SETDIFF, SETXOR, ISMEMBER.
you will see that you can get the index value returned. By default, unique returns the last index, but you are also request the first one. Additionally, you can look for unique rows, something especially useful for character data.
Here's a quick demonstration of unique acting on a vector of birthdates in my extended family (just the day of the month) and the unique values.
birthdates = [11 12 22 1 14 4 25 28 1 7 19 12] bds = unique(birthdates)
birthdates = 11 12 22 1 14 4 25 28 1 7 19 12 bds = 1 4 7 11 12 14 19 22 25 28
Now, here are the indices back into the original birthdates.
[bds, bdlast] = unique(birthdates); bdlast
bdlast = 9 6 10 1 12 5 11 3 7 8
And the first occurrences.
[bds, bdfirst] = unique(birthdates,'first'); bdfirst
bdfirst = 4 6 10 1 2 5 11 3 7 8
What I can't think of is why I care about the index. I am sure there are applications where it matters because there is related data that needs to come along. But what does the occurrence order have to do with anything?
Would you please share your code examples in which it mattered to you which instance of a non-unique element you captured? Let me know here.
Get the MATLAB code
Published with MATLAB® 7.5
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.