Question about finding the number of times an element appears in an array
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Rik
2021 年 11 月 4 日
Combining unique with histc (or histcounts) might be either safer, or more performant for larger arrays than this setup.
採用された回答
Chris
2021 年 11 月 4 日
編集済み: Chris
2021 年 11 月 4 日
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)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!