3

I want to sort rows of matrix according to a number of non zero elements in the rows consider the following example where

 a = [0 0 2;2 1 4;2 5 0]

but a should be

a =

 2     1     4
 2     5     0
 0     0     2

in the end , here is what i have come up with

 for i = 1:3
    vec(i) = sum(a(i,:)==0);%to get number of nonzero elementsin each row
 end
 a = [a vec.']
 a = sortrows(a,4) % sorting according to number of nonzero elements 
 a = [a(:,1:3)]

the code above works but does anyone have a more elegant way ?

1 Answer 1

7

You can use the following approach:

[~,I] = sort(sum(a~=0,2), 'descend');
a = a(I,:);

Result:

 a =

 2     1     4
 2     5     0
 0     0     2
1
  • Thanks that was a much better way! Commented Jun 24, 2016 at 10:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.