开发者

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

开发者 https://www.devze.com 2022-12-19 10:10 出处:网络
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 lik

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 t开发者_Go百科here is nothing built in, is there an implementation of that function available somewhere? Does someone here know how to build it?


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


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}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号