accumulating unique indices in array

3 views (last 30 days)
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)

Accepted Answer

Walter Roberson
Walter Roberson on 26 Feb 2021
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

More Answers (1)

Matt J
Matt J on 25 Feb 2021
B = histcounts(A,1:max(A)+1)
  2 Comments
Octavian
Octavian on 26 Feb 2021
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 on 26 Feb 2021
Edited: Matt J on 26 Feb 2021
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

Sign in to comment.

Categories

Find more on Data Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!