accumulating unique indices in array

2 visualizzazioni (ultimi 30 giorni)
Octavian
Octavian il 25 Feb 2021
Modificato: Matt J il 26 Feb 2021
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)

Risposta accettata

Walter Roberson
Walter Roberson il 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

Più risposte (1)

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

Accedi per commentare.

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by