MATLAB: Finding a max in a column and making all other elements equal to zero

matrix manipulationmax

I have a 5×20 matrix and i want to
1) find the max value in each column
2) make all other values in the column zero except for max
3) count the number of non-zero elements in each row
4) show the number of row that has maximum non zero element
for example
a= [ 1 3 3
3 1 2
2 1 1 ]
a= [ 0 3 3
3 0 0
0 0 0 ]
row 1 has max number of non zero elements

Best Answer

a= [ 1 3 3; 3 1 2; 2 1 1 ]
numRows = size(a,1);
maxvals = max(a)
a(a~=repmat(max(a),numRows,1)) = 0
numNonZeroInCol = sum(a~=0)
numNonZeroRow = sum(a~=0,2)
mostMaxIdx = find(numNonZeroRow == max(numNonZeroRow))