Dear all
I have got a 3D matrix, say A ( 100 by 100 by 20) containing elements of '0' , '1' , '2', '3', '4'.
I would like to know which elements happens the most frequent, except for '0'. My idea is to reshape the matrix to a vector using
A=reshape(A,100*100*20,1);
numbers = unique(A); % sorted occurrence
count=hist(A,numbers);
pointer = find(count == max(count(2:end))); % by using (2:end), I excluded the effect by '0'
value = numbers(pointer);
However, this seems redundant, any one have a better way to do that? Say, dealing with the 3D matrix straight. My 3D matrix will be very large....
Best
Yuan Chen

댓글 수: 1

hi every body , there is more simple built-in function , i just found that satisfy the title requirement : search the help for ( mode , M = mode(A,dim) ) Most frequent values in array good luck for all

댓글을 달려면 로그인하십시오.

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 12월 19일
편집: Azzi Abdelmalek 2013년 12월 19일

1 개 추천

A=randi([0 4],100,100,20); %Example
[freq,number]=max(histc(A(:),1:4))

댓글 수: 1

Yuan chen
Yuan chen 2013년 12월 19일
Thanks a lot dear Azzi, this helps a lot :)
Best
Yuan

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Cedric
Cedric 2013년 12월 19일
편집: Cedric 2013년 12월 19일

2 개 추천

Here is an example..
>> A = randi(5,[3,4,2]) - 1
A(:,:,1) =
0 3 1 4
2 0 2 0
3 3 4 1
A(:,:,2) =
3 4 4 0
0 3 2 2
1 0 4 4
>> counts = accumarray( A(:)+1, ones(numel(A),1) ) % or HISTC
counts =
6
3
4
5
6
>> mostFrequent = find( counts == max(counts) ) - 1
mostFrequent =
0
4
EDIT: note that if you want to avoid taking 0's, you can do
>> mostFrequent = find( counts(2:end) == max(counts(2:end)) )
mostFrequent =
4
I kept zeros to show that several elements can be the most frequent, so whether you use Azzi's HISTC solution or my ACCUMARRAY approach, you shouldn't use the second output argument of MAX to get the most frequent element, otherwise you'll only get the first of them (if there are multiple).

댓글 수: 3

Yuan chen
Yuan chen 2013년 12월 19일
Thanks very much Cedirc :)
Cedric
Cedric 2013년 12월 19일
편집: Cedric 2013년 12월 19일
Whether you use ACCUMARRAY or HISTC, it would actually be more efficient to create a vector of non-zero values first..
>> nz = A(A~=0) ;
>> counts = accumarray( nz, ones(size(nz)) ) ;
>> mostFrequent = find( counts == max(counts) )
mostFrequent =
4
Yuan chen
Yuan chen 2013년 12월 19일
Hi Cedric
That's very thoughtful, I was just thinking about that.!
Best

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2013년 12월 19일

댓글:

2016년 6월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by