Is there a more elegant replacement for this MATLAB loop?

I want to improve on the vectorization of my loops in MATLAB. I'm currently trying to count the occurrences of values ​​in an int list. My code is similar to this:

list = [1 2 2 3 1 3 2 2 2 1 5];
occurrence_list = zeros(1,max(list));

for x=list
    occurrence_list(x) = occurrence_list(x) + 1;
end

Is there a simple vector replacement for a loop? (Or is there a built-in MATLAB function that I skip?) I do this on fairly small datasets, so time is not a problem. I just want to improve my MATLAB coding style.

+4
source share
3 answers

In addition to the HIST / HISTC functions, you can use ACCUMARRAY to count the occurrence (as well as a number of other aggregation operations)

counts = accumarray(list(:), 1)
%# same as: accumarray(list(:), ones(size(list(:))), [], @sum)

- TABULATE ( , , ):

t = tabulate(list)
t =
            1            3       27.273
            2            5       45.455
            3            2       18.182
            4            0            0
            5            1       9.0909

, , 1 , . :

list = [3 11 12 12 13 11 13 12 12 12 11 15];
v = unique(list);
table = [v ; histc(list,v)]'

table =
     3     1
    11     3
    12     5
    13     2
    15     1

( , , )

+5

hist. .

list = [1 2 2 3 1 3 2 2 2 1 5]; 
bins = min(list):max(list);
counts = hist(list,bins);
+4

, . - HIST.

0

All Articles