find counts of unique elements in a vector in matlab

To find the counts of unique elements in a vector in Matlab, you can use the unique function to extract the unique elements and then the hist function to count the frequency of each element. Here's an example:

main.m
% create a vector
v = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];

% extract unique elements
u = unique(v);

% count frequency of each element
counts = hist(v, u);
152 chars
9 lines

This will give you a counts vector with the frequency of each unique element:

main.m
counts =
     2     1     2     1     2     1     1
52 chars
3 lines

So in the example vector v, the element 1 appears twice, the element 2 appears once, and so on.

related categories

gistlibby LogSnag