%% How do I count the occurrences of each element in a vector
%
% I came up to such questions when working on the Hardy-Ramanjan problem:
%
% <https://math.aalto.fi/opetus/Mattie/Blogi/Matlab/html/HardyRamanujan.html>
%
% After my way of counting using sort and diff presented above, I found this 
% discussion with variuos interesting solutions to related problems.
% In this "publish-worksheet" I studied and ran through many of them for my own
% learnig and joy.
%
% <https://se.mathworks.com/matlabcentral/answers/96504-how-can-i-count-the-occurrences-of-each-element-in-a-vector-in-matlab>
%% 1. Logical indexing
%
x=[10 25 4 10 9 4 4]
y = zeros(size(x));
for i = 1:length(x)
y(i) = sum(x==x(i));
end
y

%% 2. hist
x=[10 25 4 10 9 4 4]
[a,b]=hist(x,unique(x))
bar(b,a)
%{
 Solution 2 (using hist()) runs into trouble if unique(x) boils down to 
 one number (a scalar). Then hist() takes it as the number of bins to use, 
 not a bin center. Some if/else logic would catch this. Not sure if there 
 is a one line answer.
%}
ux = unique(x);
if length(ux) == 1, counts = length(x);
else counts = hist(x,ux); end
counts
%% 3. histc help
[N,BIN]=histc(x,unique(x))
%
% [N,BIN] = histc(X,EDGES,...) also returns an index matrix BIN.  If X is a
%    vector, N(K) = SUM(BIN==K)
[N(BIN);x]
%%
% 10 appears 2 times, 25 appears once, 4 appesra 3 times, ...
%% 4. Solution with histc
[a,b] = histc(x,unique(x));
y = a(b)
%% 5. arrayfun, nnz
y = arrayfun(@(t)nnz(x==t), x)
%
%% 6. Variant: Count the number of occurrences of each integer 1,2,...
%
% 
%{
I'm working with a small variant of the original problem, where I want it 
to count the number of occurrences of each whole number (till 13).
So if my input is

x = [1,1,1,2,4,5,5]

I need an output

y = [3,1,0,1,2]

How do I do this?
%}
x = [1,1,1,2,4,5,5]
y = accumarray(x(:),1)
%% 6 another sol.
%
v=[1,1,1,2,4,5,5]
numbers=unique(v)      %list of elements
count=hist(v,numbers)   %provides a count of each element's occurrence
% this will give counts. and if you want to have a nice graphical 
% representation then try this
bar(accumarray(v', 1))
shg
%{
When using hist() pay attention to Dan's comment above pointing out a flaw 
in the approach. This flaw is not shared by Andrei's histc approach above.
%}


%%