如果你想避免循环,你可以使用reshape 和sort 的组合来达到你想要的效果:
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
最后,您可以使用reshape 恢复原始尺寸:
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);