Filter löschen
Filter löschen

Question about finding the number of times an element appears in an array

1 Ansicht (letzte 30 Tage)
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
Lewis
Lewis am 4 Nov. 2021
E.g. for A=[1 2 4] it will create B = [1 1 0 1]
Rik
Rik am 4 Nov. 2021
Combining unique with histc (or histcounts) might be either safer, or more performant for larger arrays than this setup.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Chris
Chris am 4 Nov. 2021
Bearbeitet: Chris am 4 Nov. 2021
A = randi(9,2)
A = 2×2
8 8 5 9
A(:) formats A in a column vector.
A(:)
ans = 4×1
8 5 8 9
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
ans = 4×9 logical array
0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1
Summing across dimension 1 (the default):
B=sum(A(:)==1:9)
B = 1×9
0 0 0 0 1 0 0 2 1

Weitere Antworten (0)

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by