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

112 views Asked by At

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?

2

There are 2 answers

0
Ray On
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.

2
Luis Mendo On

Two other possibilities, in addition to histc:

  1. 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)));
    
  2. 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).