如何在保持索引行的顺序与排序行匹配的同时对数组进行排序?

时间:2016-10-18 18:28:08

标签: matlab sorting

最简单的方法是通过excel向您展示:

未排序:

Need to sort second column while keeping the first one matching

排序:

Second column sorted, first column follows second column

这个例子是excel,但是我需要在matlab中用数千个条目做同样的事情(如果可能的话,用2行)。

到目前为止,这是我的代码:

%At are random numbers between 0 and 2, 6000 entries.

    [sorted]=sort(At);
    max=sorted(end);
    min=sorted(1);
%need the position of the min and max

但这只是排序的一行,第二行没有数字,也没有索引。我如何添加一个并将其保留在第一行之后?

谢谢!

2 个答案:

答案 0 :(得分:2)

我无法访问Matlab,但请尝试

[sorted, I] = sort(At);

我将成为At的指数的相应向量。有关详细信息,请参阅Matlab Documentation

答案 1 :(得分:1)

你有几个选择。对于您只需要索引的简单情况,docs中列出的sort的第四种形式已经为您执行此操作:

[sorted, indices] = sort(At);

在这种情况下,At(indices)sorted相同。

如果您的“索引”实际上是另一个不同的数组,则可以使用sortrows

toSort = [At(:) some_other_array(:)];
sorted = sortrows(toSort);

在这种情况下,sorted(:, 1)将是第一个示例中的sorted数组,sorted(:, 2)将是根据At排序的另一个数组。

sortrows接受第二个参数,该参数告诉您要排序的列。这可以是单列或列列表,例如Excel。它还可以提供第二个输出参数,即索引,就像常规sort一样。