MATLAB: Guys!! help me in code for finding out maximum value in each row of a matrix and make others as zero value in such a way that if i need 2 max in a row it should display without changing the index value and make others as zero

find functionwith sort

Eg: a=[1 2 3; 4 5 6; 7 8 9] if i need R=2 means it should display like rowmax=[0 2 3; 0 5 6; 0 8 9]

Best Answer

  • Here is a general solution for matrices of decimal values arranged into any sequence. It uses MATLAB's rather powerful indexing ability, and does not require that the values are integers >= one.
    >> R = 2;
    >> A = [1,2,3;4,5,6;7,8,9];
    >> [~,B] = sort(A,2);
    >> [~,B] = sort(B,2);
    >> X = B>size(A,2)-R;
    Note the two sort operations. Here are two alternatives, the first creates a new matrix:
    >> C = zeros(size(A));
    >> C(X) = A(X)
    C =
    0 2 3
    0 5 6
    0 8 9
    The second alters the original matrix:
    >> A(~X) = 0
    A =
    0 2 3
    0 5 6
    0 8 9
    You can pick which one suits you best. We can also demonstrate it on a slightly more interesting test-case, where the values are not arranged in sequence:
    >> A = [randperm(5);randperm(5);randperm(5)]
    A =
    5 4 2 3 1
    4 3 2 5 1
    5 2 4 3 1
    >> [~,B] = sort(A,2);
    >> [~,B] = sort(B,2);
    >> X = B>size(A,2)-R;
    >> A(~X) = 0
    A =
    5 4 0 0 0
    4 0 0 5 0
    5 0 4 0 0
    Which shows that only the highest two values have been retained, all others values are now zero.