# How to accumulate the number of appearance of an integer sequence?

I have a sequence of integers, say arr = [1,5,2,2,5,1].

I need a structure, say Counter, that can tell me how many times the integer appears.

I have the following code but it won't work since isfield cannot be used in this way.

for i = 1 : length(arr) if ~isfield(Counter, i) Counter{i} = 0; end Counter{i} = Counter{i} + 1 end

So is there any elegant way that can accumulate the number of appearance of an integer sequence?

## Answers

A = [1 2 1 2 3 3 1 4 5 5 6]; numbers = unique(A); % [1, 2, 3, 4, 5, 6] unique elements count = histc(A, numbers); % [3, 2, 2, 1, 2, 1] occurrence of the element

The two core commands are unique and histc.

Two other possibilities, in addition to histc:

Use bsxfun to test for equality and then sum all coincidences for each number:

A = [1 2 1 2 3 3 1 4 5 5 6]; count = sum(bsxfun(@eq, A(:), min(A):max(A)));

Use accumarray to sum 1 for each occurrence of each number:

count = accumarray(A(:)-min(A)+1, 1, []).';

In both cases, count(1) is the number of ocurrences of min(A), count(2) is the number of ocurrences of min(A)+1, ..., count(end) is the number of occurrences of max(A) (some of which may be zero).