accumulating unique indices in array

3 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Data Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by