Fast way to sort array by sum of strings in matlab
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 to share
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 to share
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 to share