E.g. for A=[1 2 4] it will create B = [1 1 0 1]
Question about finding the number of times an element appears in an array
조회 수: 1 (최근 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에서 Multidimensional Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!