developer tip

행렬에서 주어진 값의 요소 수를 어떻게 계산할 수 있습니까?

optionbox 2020. 10. 31. 09:37
반응형

행렬에서 주어진 값의 요소 수를 어떻게 계산할 수 있습니까?


누구든지 행렬에 값이 나타나는 횟수를 계산하는 방법을 알고 있습니까?

예를 들어 M평일 (1-7) 값을 저장 하는 1500 x 1 행렬 (벡터)이있는 경우 일요일 (1), 월요일 (2), ..., 토요일 (7) 수를 어떻게 계산할 수 있습니까? 에 저장되어 M있습니까?


배열의 고유 값 결정 및 계산 을 참조 하십시오 .

또는의 발생 횟수를 계산하려면 다음을 5수행하십시오.

sum(your_matrix == 5)

다음은 고유 한 요소를 계산하는 모든 방법에 대한 목록입니다.

M = randi([1 7], [1500 1]);

옵션 1 : 표 작성

t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);

옵션 2 : hist / histc

counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );

옵션 3 : accumarray

counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);

옵션 4 : 정렬 / 차이

[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);

옵션 5 : arrayfun

counts5 = arrayfun( @(x)sum(M==x), unique(M) );

옵션 6 : bsxfun

counts6 = sum( bsxfun(@eq, M, unique(M)') )';

옵션 7 : 스파 스

counts7 = full(sparse(M,1,1));

1부터 7까지의 모든 값에 대해이 작업을 한 번에 수행 할 수있는 한 가지 방법은 ACCUMARRAY 함수를 사용하는 것 입니다 .

>> M = randi(7,1500,1);  %# Some random sample data with the values 1 through 7
>> dayCounts = accumarray(M,1)  %# Will return a 7-by-1 vector

dayCounts =

   218       %# Number of Sundays
   200       %# Number of Mondays
   213       %# Number of Tuesdays
   220       %# Number of Wednesdays
   234       %# Number of Thursdays
   219       %# Number of Fridays
   196       %# Number of Saturdays

w에 주 번호가 포함되어 있다고 가정합니다 ([1 : 7]).

n = histc(M,w)

M의 숫자 범위를 모르는 경우 :

n = histc(M,unique(M))

명령에 의한 SQL 그룹과 같습니다!


이것은 우리가 행렬에 대한 연산을 수행하는 완벽한 원인이 될 것입니다. 답은 단일 숫자 여야합니다.

sum(sum(matrix==value))

이것은 Matlab Central File Exchange에서 사용할 수있는 매우 좋은 기능 파일입니다.

countmember.m 링크

이 함수 파일은 완전히 벡터화되어 있으므로 매우 빠릅니다. 또한 aioobe의 답변에서 언급되는 기능과 비교할 때이 기능은 accumarray 기능을 사용하지 않기 때문에 이전 버전의 Matlab 과도 호환됩니다. 또한 숫자 형 배열뿐 아니라 셀형 배열에서도 작동합니다.

SOLUTION : You can use this function in conjunction with the built in matlab function, "unique".

occurance_count = countmember(unique(M),M)

occurance_count will be a numeric array with the same size as that of unique(M) and the different values of occurance_count array will correspond to the count of corresponding values (same index) in unique(M).


Use nnz instead of sum. No need for the double call to collapse matrices to vectors and it is likely faster than sum.

nnz(your_matrix == 5)

Doc

참고URL : https://stackoverflow.com/questions/2880933/how-can-i-count-the-number-of-elements-of-a-given-value-in-a-matrix

반응형