Matlab 对向量的每个范围进行排序

Matlab 对向量的每个范围进行排序,matlab,sorting,Matlab,Sorting,给定以下向量: 5 4 1 2 3 1 4 5 3 2 3 2 1 5 4 _________ _________ _________ 我想对向量的每5个元素应用排序。因此,结果将是: 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 _________ _________ _________ 如何在MATLAB中实现无循环 另外,我还想提取排序索引以将其应用于另一个向量。如果您想避免循环,可以结合使用重塑和排序来实现您想要的: b = [5 4 1 2 3 1 4 5 3 2

给定以下向量:

5 4 1 2 3 1 4 5 3 2 3 2 1 5 4
_________ _________ _________
我想对向量的每5个元素应用排序。因此,结果将是:

1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 
_________ _________ _________
如何在MATLAB中实现无循环


另外,我还想提取排序索引以将其应用于另一个向量。

如果您想避免循环,可以结合使用
重塑
排序
来实现您想要的:

b = [5 4 1 2 3 1 4 5 3 2 3 2 1 5 4];
b2 = reshape(b, [5 3]);           % Reshape your array to be a [5x3] matrix
b2_new = sort(b2, 1);             % Sort each column of your matrix seperately
b_new = reshape(b2_new, size(b)); % Reshape the outcome back to the original dimensions
或者,全部放在一行中:

b_new = reshape(sort(reshape(b, [5 3]), 1), size(b));
当然,您必须更改数字5和3以适合您的问题。重要的是要确保为重塑命令(在本例中为
5
)提供的第一个值等于要排序的子向量的长度,因为Matlab是列主向量

编辑:

如果要对一个特定向量进行排序,然后对其他向量应用相同的重新排序,可以使用
sort
函数的可选第二个输出参数。使用与上述相同的向量:

b = [5 4 1 2 3 1 4 5 3 2 3 2 1 5 4];
b2 = reshape(b, [5 3]);
收益率:

b2 = 5 1 3
     4 4 2
     1 5 1
     2 3 5
     3 2 4
假设要对第一列进行排序,并对第二列和第三列应用相同的重新排序,则需要:

[~,idx] = sort( b2(:,1) );   % Sorts the first column of b2, and stores the index map in 'idx'
这将产生
idx=[3 4 5 2 1]
。现在,您可以使用这些索引对所有列进行排序:

b2_new = b2(idx,:);
b2_new =
     1     5     1
     2     3     5
     3     2     4
     4     4     2
     5     1     3
最后,您可以使用
重塑
回到原始尺寸:

b_new = reshape(b2_new, size(b));

编辑2:

如果您想将
b
的重新排序作为一个整体存储起来,并将其应用到新的向量
c
,那么我们必须更具创造性。以下是一种方法:

b = [5 4 1 2 3 1 4 5 3 2 3 2 1 5 4];
b2, = reshape(b, [5 3]);

% Sort each column of your matrix seperately, and store the index map
[~,idx] = sort(b2, 1);

% Alter the index map, such that the indices are now linear indices:
idx = idx + (0:size(idx,2)-1)*size(idx,1);

% Reshape the index map to the original dimensions of b:
idx = reshape(idx, size(b));

% Now sort any array you want using this index map as follows:
b_new = b(idx);
c_new = c(idx);

非常感谢你!是否可以提取排序向量(重塑)以将其应用于另一个向量,我需要以与对第一个向量排序相同的方式对其进行排序?我指的是包含索引的排序函数的第二个输出。这是你的意思吗,Humam?我不完全确定。如果您想存储
b
的整个重新排序,并将其应用于不同的向量
c
,我们必须更具创造性。是的,我想要其他选项。然而,从你的想法。我可以找到另一个问题的解决办法。我真的很感谢你的帮助!谢谢啊,我想。没问题!我已经做了第二次编辑,显示了您可以采取的一种方法。你可以把它当作支票,自己也可以试试:-)