Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: Behavior of the unique function

Tags:

matlab

I'm currently migrating code from R2012a to R2013b.

I noticed that the unique function behavior has changed:

R2012a

>> size(unique([]))

ans =

     0     0

R2013b

>> size(unique([]))

ans =

     0     1

It seems counter-intuitive to me that a 0x0 matrix would become a 0x1 matrix after removing doublons, which is essentially what the unique function does. Does anybody has a rationale for this?

like image 631
Eric Salemi Avatar asked Dec 05 '13 10:12

Eric Salemi


People also ask

What does the unique function in Matlab do?

Use unique to find the unique elements in the concatenated vector [x;y] . The unique function performs exact comparisons and determines that some values in x are not exactly equal to values in y . These are the same elements that have a nonzero difference in x-y . Thus, c contains values that appear to be duplicates.

What does Accumarray do in Matlab?

The behavior of accumarray is similar to the functions groupsummary and groupcounts for computing summary statistics by group and counting the number of elements in a group, respectively. For more grouping functionality in MATLAB®, see Preprocessing Data.

How do you find unique rows in a matrix?

Efficient Approach: Using Hashing, we can store the key as a string containing all the characters in that row and its frequency as the value. And traverse all the rows in the map and if its frequency is 1 then count it as unique.

What is a unique value in an array?

You can find the distinct values in an array using the Distinct function. The Distinct function takes the array as an input parameter and returns another array that consists only of the unique, or non-duplicate, elements. The following example shows how to find the distinct values in an array.


2 Answers

The behaviour has changed with R2013a, if you need the old behaviour use:

size(unique([],'legacy'))

If you need code for both versions, I would recommend to write some function which calls unique(x,'legacy') for new versions and unique(x) for old versions.

btw: same issue with union, intersect, setdiff, setxor and ismember

like image 170
Daniel Avatar answered Sep 24 '22 21:09

Daniel


I don't know whether this is the reason, but it does come with an advantage.

Now you will see that unique(M) gives the same output as unique(M(:)), even if M is empty.

Example:

M = magic(5);
isequal(size(unique(M)), size(unique(M(:)))); 
M = [];
isequal(size(unique(M)), size(unique(M(:)))); 

The latter returns false on old versions of matlab, this may be confusing.

like image 31
Dennis Jaheruddin Avatar answered Sep 23 '22 21:09

Dennis Jaheruddin