Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Mathematica have a function equivalent to Matlab's "unique" function

Is there a Mathematica function that provides results equivalent to the unique() function in MATLAB? I realize I could use the Union[] function to obtain the unique elements of a list, but I would like something equivalent to the three-result version of the function that provides index arrays that map between the input array and the array of unique values.

If there is nothing built in, is there an implementation of that function available somewhere? Does someone here know how to build it?

like image 660
clartaq Avatar asked Feb 04 '10 22:02

clartaq


3 Answers

You can easily build similar functionality yourself with Mathematica's Position[]. E.g. given a list of numbers you could do the following:

In[1] := A = {1, 5, 2, 3, 7, 3, 2, 8, 6, 5, 9, 2, 1};
In[2] := {#, Flatten[Position[A, #]]} & /@ Union[A]
Out[2]:= {{1, {1, 13}}, {2, {3, 7, 12}}, {3, {4, 6}}, {5, {2, 10}}, {6, {9}}, {7, {5}}, {8, {8}}, {9, {11}}}

to get the list of unique elements and the indices of where they appear in the original list. To replicate exactly the functionality of Matlab's Unique(), especially for

[b,m,n] = unique(A)

you need

b = Union[A];
m = Last[Position[A, #]] & /@ b // Flatten;
n = Position[b, #] & /@ A // Flatten;

which now provide the desired behavior

In[1] := A[[#]] & /@ m == b
Out[1]:= True

In[2] := b[[#]] & /@ n == A
Out[2]:= True
like image 132
Timo Avatar answered Nov 03 '22 12:11

Timo


Try Length[Union[x]]. If x=[1,0,1,1,1], then you'll get Length[Union[x]] = 2.

like image 41
Cambise Homa Avatar answered Nov 03 '22 13:11

Cambise Homa


There's a simple way:

a={1,2,3,4,5,5,5,4,3,2}

  {1,2,3,4,5,5,5,4,3,2}

uniques = DeleteDuplicates[a]

  {1,2,3,4,5}
like image 2
earnric Avatar answered Nov 03 '22 14:11

earnric