MATLAB: How to select the highest values form each column and set the other values to zero.

effort will not be takenno attemptselect highest values

If
A=[0.1290 0.2880 0.0193 0.2064 0.5245 0.5067 0.0255 0.2789;
0.2721 0.3500 0.0916 0.0913 0.5780 0.4616 0.3746 0.4651;
0.2011 0.2672 0.3051 0.1836 0.5149 0.3960 0.3730 0.3996;
0.0610 0.0374 0.0366 0.0453 0.0633 0.2699 0.2800 0.2522]
I want to generate the matrix from A such that it should contain the highest two values present in each column and the rest of values should be set to zero and it should diaplay in the following manner.
A=
[0 0.2880 0 0.2064 0.5245 0.5067 0 0;
0.2721 0.3500 0.0916 0 0.5780 0.4616 0.3746 0.4651;
0.2011 0 0.3051 0.1836 0 0 0.3730 0.3996;
0 0 0 0 0 0 0 0]
Could anyone please help me on this.

Best Answer

[m,n] = size(A);
[~,ii] = sort(A);
A(bsxfun(@plus,ii(1:end-2,:),(0:n-1)*m)) = 0;
or
[m,n] = size(A);
[~,ii] = sort(A);
A(ii(1:end-2,:) + (0:n-1)*m) = 0;