Count number of times value occurs

7 ビュー (過去 30 日間)
dan berkowitz
dan berkowitz 2018 年 10 月 12 日
コメント済み: Bruno Luong 2021 年 7 月 6 日
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
Bruno Luong 2018 年 10 月 12 日
編集済み: Bruno Luong 2018 年 10 月 12 日
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)'
  3 件のコメント
Benedict Greenwood
Benedict Greenwood 2021 年 7 月 6 日
Cheers Bruno great piece of code! Can I double-check why the bottom line is necessary? For my data the output is the same without the bottom line (although not transposed because of the apostrophe).
Bruno Luong
Bruno Luong 2021 年 7 月 6 日
The last line is needed in case your data is not consecutive integers 1, 2, 3 ...

サインインしてコメントする。

その他の回答 (2 件)

Image Analyst
Image Analyst 2018 年 10 月 12 日
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])
  1 件のコメント
Bruno Luong
Bruno Luong 2018 年 10 月 12 日
編集済み: Bruno Luong 2018 年 10 月 12 日
@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
Bruno Luong 2018 年 10 月 12 日
編集済み: Bruno Luong 2018 年 10 月 12 日
Assume a and b are row vectors, and one of them is not too big
c = sum(a(:)==b,1)

カテゴリ

Help Center および File ExchangeHistograms についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by