Fast way to sort array by sum of strings in matlab

Here's a small example of what I want. Given the following array:

1 1 2
2 2 1
1 1 1
1 1 6

      

Sorted (the sum of the lines is indicated in brackets):

1 1 6 (8)
2 2 1 (5)
1 1 2 (4)
1 1 1 (3)

      

Is there a quick way to achieve this in Matlab?

+1


source to share


5 answers


Since it sort

returns the indices in order as well as the sorted matrix, you can use these indices to access the original data - try this:



% some data
A = [
  1 1 2;
  2 2 1;
  1 1 1;
  1 1 6;
];

% compute the row totals
row_totals = sum(A,2);

% sort the row totals (descending order)
[sorted, row_ids] = sort(row_totals, 'descend');

% and display the original data in that order (concatenated with the sums)
disp([A(row_ids,:), row_totals(row_ids)])

>>> 
 1     1     6     8
 2     2     1     5
 1     1     2     4
 1     1     1     3

      

+7


source


The ugliest one-liner I could come up with:

>> subsref( sortrows( [sum(A,2) A], -1 ), struct('type','()','subs',{{':',1+(1:size(A,2))}}) )

ans =

 1     1     6
 2     2     1
 1     1     2
 1     1     1

      



Disclaimer: I don't think anyone should write code like this, but it's good practice to keep your Matlab skills sharp.

+4


source


Just do something very simple as follows

temp = [1 1 2
        2 2 1
        1 1 1
        1 1 6];
rowSums = sum(temp,2);
[~,idx] = sort(rowSums,'descend');
output = [temp(idx,:),rowSums(idx)];

      

EDIT

Modified the above code to make sure the sum is added to the last column. I didn't notice that this was a requirement when I first read the question.

+2


source


I'm leaving this for you to judge if it's uglier than @ Shai's:

fliplr(diff([sortrows(fliplr(-cumsum(A,2))) zeros(size(A,1),1) ],1,2))

      

+2


source


Let some matrix multiplication

>> sortrows([sum(A,2) A], -1)*[zeros(1,size(A,2)); eye(size(A,2))]

      

returns

ans =
     1     1     6
     2     2     1
     1     1     2
     1     1     1

      

+1


source







All Articles