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

1 回表示 (過去 30 日間)
Lewis
Lewis 2021 年 11 月 4 日
コメント済み: Lewis 2021 年 11 月 4 日
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 件のコメント
Lewis
Lewis 2021 年 11 月 4 日
E.g. for A=[1 2 4] it will create B = [1 1 0 1]
Rik
Rik 2021 年 11 月 4 日
Combining unique with histc (or histcounts) might be either safer, or more performant for larger arrays than this setup.

サインインしてコメントする。

採用された回答

Chris
Chris 2021 年 11 月 4 日
編集済み: Chris 2021 年 11 月 4 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by