# Count number of times value occurs

25 views (last 30 days)
dan berkowitz on 12 Oct 2018
Commented: Bruno Luong on 6 Jul 2021
Hi,
I have an array a = [ 1 2 3 2 2 3 1], and another array, b = [1:5].
How can I create an array c, that counts the number of times that each value in b occurs in a?
I want c = [2 3 2 0 0] (ie. 1/2/3/4/5 from b, appears 2/3/2/0/0 times in a)
Any help would be appreciated. Thanks,
DB

Bruno Luong on 12 Oct 2018
Edited: Bruno Luong on 12 Oct 2018
Method for large a and b
[u,~,j] = unique(b(:));
[b, i] = ismember(a(:),u);
c = accumarray(i(b),1,size(u));
c = c(j)'
Bruno Luong on 6 Jul 2021
The last line is needed in case your data is not consecutive integers 1, 2, 3 ...

Image Analyst on 12 Oct 2018
Yet another way to get the histogram is to use histcounts():
a = [ 1 2 3 2 2 3 1]
b = [1:5]
counts = histcounts(a, 'BinEdges', [b, inf])
Bruno Luong on 12 Oct 2018
Edited: Bruno Luong on 12 Oct 2018
@Dan: double check if you really want IA's method, for example with
a = [2];
b = [1 3];
counts = histcounts(a, 'BinEdges', [b, inf])
> counts =
1 0
to me 1 and 3 from b appear 0 time in a.

Bruno Luong on 12 Oct 2018
Edited: Bruno Luong on 12 Oct 2018
Assume a and b are row vectors, and one of them is not too big
c = sum(a(:)==b,1)