MATLAB: Flipping the rows in a matrix to rearrange according to the weighted sum of the row

rearranging rows of matrix

Hello, I have a matrix
A=[0.6 0.4 0.9 0.7;0.8 0.7 0.9 0.5;0.8 0.6 0.5 0.4;0.8 0.5 0.6 0.5]
I want to rearrange the rows in the matrix according sum of the row in a descending order. Here,
sum(row 1) = 2.6
sum(row 2) = 2.9
sum(row 3) = 2.3
sum(row 4) = 2.4
Therefore, the new matrix becomes:
[row2;row1;row4;row3]
Thanks

Best Answer

  • >> A=[0.6 0.4 0.9 0.7;0.8 0.7 0.9 0.5;0.8 0.6 0.5 0.4;0.8 0.5 0.6 0.5]
    A =
    0.6 0.4 0.9 0.7
    0.8 0.7 0.9 0.5
    0.8 0.6 0.5 0.4
    0.8 0.5 0.6 0.5
    >> [~,idx] = sort(-sum(A,2))
    idx =
    2
    1
    4
    3
    >> A(idx,:)
    ans =
    0.8 0.7 0.9 0.5
    0.6 0.4 0.9 0.7
    0.8 0.5 0.6 0.5
    0.8 0.6 0.5 0.4