I would like to be able to return the count of occurences of each element in a vector.
For example if I have a vector:
x=[10 25 4 10 9 4 4]
I expect the result to be
y=[2 1 3 2 1 3 3].
While there is no single function in MATLAB to count occurrences of each element, there are a few ways to count elements in a vector:
1. Logical Indexing:
The following code snippet will give the desired output:
y = zeros(size(x)); for i = 1:length(x) y(i) = sum(x==x(i)); end
For MATLAB R2016b and later, you can use implicit expansion to further simplify the code:
y = sum(x==x')
You can use the "hist" and "unique" functions as shown here to do the same:
x = [10 25 4 10 9 4 4] [a,b]=hist(x,unique(x))
3. Third-Party Tools:
For another workaround, see the following file, 'CountMember.m', that was contributed by a MATLAB user to do the same from a single function:
Note that MathWorks does not guarantee or warrant the use or content of submissions to the MATLAB Central File Exchange. Any questions, issues, or complaints should be directed to the contributing author.
This is kind of awkward since it requires using the input array within the anonymous function, but:
y = arrayfun(@(t)nnz(x==t), x);
should do the trick, too.
Hi, I want to count the number of followed occurrences of each element in a vector.
So if my input is
x = [1 1 1 2 2 1 1 2 5 5]
I need an output
y = [1 2 1 2 5;3 2 2 1 2] How do I do this?