It'd be hard to beat this for efficiency:
elements = unique(A);
counts = histc(A(:), elements);
Question
I have this vector lets say
A = [1; 2; 3; 1; 2; 3; 1; 2; 3]
How can I find the unique elements and their count something like this?
1 = 3
2 = 3
3 = 3
I can definitely loop over the individual elements and use some naive techniques. I don't want that kind of solution because my real data will be in the range of millions so I cannot just loop over each element.
What is the most efficient way to do it in matlab?
Solution
It'd be hard to beat this for efficiency:
elements = unique(A);
counts = histc(A(:), elements);
OTHER TIPS
Notlikethat's answer is the way to go. But its efficiency (computation time) can actually be improved:
sA = sort([A(:); inf]); %// sort A
ind = diff(sA)~=0; %// index of last element of each run of equal values
elements = sA(ind); %// unique elements
counts = diff([0; find(ind)]); %// lengths of runs
Benchmarking:
clear all
A = randi(100,1e6,1); %// Example data. Large column vector
%// Notlikethat's answer
tic
elements = unique(A);
counts = histc(A(:), elements);
toc
clear elements counts
%// This answer
tic
sA = sort([A(:); inf]);
ind = diff(sA)~=0;
elements = sA(ind);
counts = diff([0; find(ind)]);
toc
Elapsed time is 0.175594 seconds.
Elapsed time is 0.076032 seconds.