Question about finding the number of times an element appears in an array
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Can someone explain why/how this code works in creating an array B which corresponds to the number of each integer from 1-9 in array A?
c=[1:9]
B=sum(A(:)==c, 1)
2 Kommentare
Rik
am 4 Nov. 2021
Combining unique with histc (or histcounts) might be either safer, or more performant for larger arrays than this setup.
Akzeptierte Antwort
Chris
am 4 Nov. 2021
Bearbeitet: Chris
am 4 Nov. 2021
A = randi(9,2)
A(:) formats A in a column vector.
A(:)
A(:)==c compares the column to each element of c (possible because the dimensions of a and c are orthogonal), returning an nx9 matrix with ones where the comparison is true.
A(:)==1:9
Summing across dimension 1 (the default):
B=sum(A(:)==1:9)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!