accumulating unique indices in array

2 ビュー (過去 30 日間)
Octavian
Octavian 2021 年 2 月 25 日
編集済み: Matt J 2021 年 2 月 26 日
Dear All,
I have a vector A = [1;1;2;4;2;7;3;2;5;4;7;1..];
I need to count the no of times each index shows in a vector B = [1;2;1;1;2;1;1;3;1;2;2;3..].
Intuitively, I think it may involve unique and accummaray, but I just cannot get it to work, thank you,
Octavian
(R2018a)

採用された回答

Walter Roberson
Walter Roberson 2021 年 2 月 26 日
A = [1;1;2;4;2;7;3;2;5;4;7;1];
B = [1;2;1;1;2;1;1;3;1;2;2;3];
ua = unique(A);
[found, idx] = ismember(B, ua);
[ua, accumarray(idx(found), 1, [length(ua),1])]
ans = 6×2
1 6 2 4 3 2 4 0 5 0 7 0

その他の回答 (1 件)

Matt J
Matt J 2021 年 2 月 25 日
B = histcounts(A,1:max(A)+1)
  2 件のコメント
Octavian
Octavian 2021 年 2 月 26 日
That is not working, B= [3,3,1,2,1,0,2] is different from B above; I do not need simple binning, but row to row index counts, see B above, thank you.
Matt J
Matt J 2021 年 2 月 26 日
編集済み: Matt J 2021 年 2 月 26 日
A = [1;1;2;4;2;7;3;2;5;4;7;1];
B = [1;2;1;1;2;1;1;3;1;2;2;3];
Au=unique(A);
counts = histcounts( B(ismember(B,Au)) , [Au(:); Au(end)+1] );
[Au(:),counts(:)]
ans = 6×2
1 6 2 4 3 2 4 0 5 0 7 0

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by