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:

  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).


Need Your Help

Display Notification clear notification in android

android google-cloud-messaging

i am developing application in that i have to receive notification from GCM ,i am successfully receive notification but it have only display recent notification but i want to display all notificati...

What can cause Bonjour to not call me back during browsing?

iphone cocoa bonjour mdns

I have a rather popular Bonjour-based application in App Store. It works perfectly, but around 0.2% of my users report a bizarre bug: "no arrows appear on the edges of the screen, so I can't share ...