MATLAB: Is it possible to vectorize this

MATLABspeedupvectorization

I want to find the most occurring element in the matrix in column wise excluding zeror elements.
e.g if A = [1 2 0 3 4 6; 9 3 4 0 9 5; 4 3 0 5 6 7; 3 7 7 3 0 0;1 1 8 8 4 8; 0 0 0 0 4 2; 0 0 0 0 0 0]'
The result is a cell matrix B
B={[1 2 3 4 6], [9], [4 3 5 6 7],[3 7], [8],[4 2], nan}
So most occurring elements is a cell array.
loops are inefficient for lage matrix.
Thanks in advance….

Best Answer

A = [1 2 0 3 4 6; 9 3 4 0 9 5; 4 3 0 5 6 7; 3 7 7 3 0 0;1 1 8 8 4 8; 0 0 0 0 4 2; 0 0 0 0 0 0]
A = 7×6
1 2 0 3 4 6 9 3 4 0 9 5 4 3 0 5 6 7 3 7 7 3 0 0 1 1 8 8 4 8 0 0 0 0 4 2 0 0 0 0 0 0
B = accumarray(repmat((1:height(A)).',width(A),1),A(:), [],@(x)modeall(nonzeros(x)))
B = 7×1 cell array
{5×1 double} {[ 9]} {5×1 double} {2×1 double} {[ 8]} {2×1 double} {[ NaN]}
celldisp(B)
B{1} = 1 2 3 4 6 B{2} = 9 B{3} = 3 4 5 6 7 B{4} = 3 7 B{5} = 8 B{6} = 2 4 B{7} = NaN
function m = modeall(x)
[~,~,m] = mode(x);
if isempty(m{1}) % Handle empty case
m{1} = nan;
end
end