在Matlab中针对行总和对数组进行排序的快速方法 [英] Quick way to sort an array with respect to row sum in Matlab

查看:270
本文介绍了在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 (row sum is shown in parenthesis):

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

在Matlab中有快速的方法吗?

Is there a quick way to achieve this in Matlab?

推荐答案

由于sort会按顺序返回索引以及排序后的矩阵,因此您可以使用这些索引来访问原始数据,请尝试以下操作:

Since sort returns the indexes 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

这篇关于在Matlab中针对行总和对数组进行排序的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆