简体   繁体   中英

How can I count number of occurrences of unique row in MATLAB ?

I have a matrix like following,

A =

     1     2     3
     4     5     6
     7     8     9
    10    11    12
     4     5     6
     7     8     9
     4     5     6
     1     2     3

I could extract unique rows in this matrix using command A_unique = unique(A,'rows') and result as follows

A_unique =

     1     2     3
     4     5     6
     7     8     9
    10    11    12

I need to find number of times each rows exists in the main matrix A Some thing like following

A_unique_count =

     2
     3
     2
     1

How can I find count of unique rows? Can anyone help? Thanks in Advance

Manu

The third output of unique gives you the index of the unique row in the original array. You can use this with accumarray to count the number of occurrences.

For example:

A = [1     2     3
     4     5     6
     7     8     9
    10    11    12
     4     5     6
     7     8     9
     4     5     6
     1     2     3];

[uniquerow, ~, rowidx] = unique(A, 'rows'); 
noccurrences = accumarray(rowidx, 1)

Returns:

noccurrences =

     2
     3
     2
     1

As expected

I would recommend @excaza's approach . But just for variety:

A_unique_count = diff([0; find([any(diff(sortrows(A), [], 1), 2); 1])]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM