2
votes

I have a 250000x2-matrix in matlab, where in the first row I have a degree (int, 0-360°), and in the second a float-value corresponding to this value. My target is to count each occurence of a degree-value-pair (e.g. a row), and write the result in a nx3-matrix. n corresponds here with the number unique rows.
Thus my first step was to get all unique values (using unique(M, 'rows')) which works. But now I want to count all unique values. This was done by the following approach:

uniqu_val = unique(values, 'rows');
instance = histcounts(values(:), uniqu_val);

Here I have to enter a vector as second element, and not a matrix (uniqu_val is a nx2-dim-matrix). But I want to get the number of occurence for each unique row, therefore I can not use only one column of the matrix uniqu_val. In short: I want to use histcounts not only for a 1D-matrix as edge-value, but for a 2D-matrix. How can I solve this problem?

1

1 Answers

2
votes

You can use the third output from unique and then use histcounts like so -

%// Find the unique rows and keep the order with 'stable' option
[uniq_val,~,row_labels] = unique(values, 'rows','stable')

%// Find the counts/instances
instances = histcounts(row_labels, max(row_labels))
%// OR with HISTC: instances = histc(row_labels, 1:max(row_labels))

%// Output the unique rows alongwith the counts 
out = [uniq_val instances(:)]

Sample run -

>> values
values =
     2     1
     3     1
     2     3
     3     3
     1     2
     3     3
     1     3
     3     1
     3     2
     1     2
>> out
out =
     2     1     1
     3     1     2
     2     3     1
     3     3     2
     1     2     2
     1     3     1
     3     2     1