MATLAB: Most frequent value in a 3D matrix other than 0

frequent value

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

Best Answer

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