matlab怎么对向量进⾏排序,matlab-对向量的每个范围进⾏排
序-堆栈内存溢出
如果要避免循环,可以结合使⽤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);
sort命令排序% 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);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论