TravellingSalesWoman
TravellingSalesWoman

Reputation: 133

Counting Different unique numbers in matlab

I want to count the number of different numbers in the matrix other than -1. For example the different numbers in the following matrix are 6 as the different numbers are 8 9 3 5 2 1

   -1  -1  8  9   
    3   5 -1  3
    2   3  3  1 

How can I do that with MATLAB ?

Upvotes: 2

Views: 126

Answers (1)

Divakar
Divakar

Reputation: 221774

I. Using unique

Use unique with its 'stable' option to keep the order -

A1 = reshape(A.',1,[])  %// A is your input matrix
out = unique(A1(A1~=-1),'stable')  %// out is your desired output

Output -

out =
     8     9     3     5     2     1

If you don't care about keeping the order of the unique numbers, you can use unique without the 'stable' option -

A1 = unique(A)
out = A1(A1~=-1)

which can be converted to a dense one-liner if you are into those -

out = nonzeros(unique(A).*(unique(A)~=-1))

II. Using setdiff

Use setdiff with 'stable' option to keep the order -

A1 = reshape(A.',1,[])  %// A is your input matrix
out = setdiff(A1,-1,'stable')  %// out is your desired output

One-liner using default version of setdiff, if you don't care about the order -

out = setdiff(A,-1)

Finally, you can get the count of those unique numbers with numel(out).

Upvotes: 6

Related Questions