为什么会这样
t = magic(4);
k = 1:4;
tt(k,:) = sort(t(k,:)) %
对每一列内的值进行排序(交换行和列什么都不做), 但是这个
t = magic(4);
for k = 1:4
tt(k,:) = sort(t(k,:))
end
按预期对行内的值进行排序?
最佳答案
在下面
t = magic(4);
k = 1:4;
tt(k,:) = sort(t(k,:)) %
t(k,:)
是一个 4x4 矩阵。因此,sort
将应用其默认的 1-dim 排序,即 w.r.t.行。请注意,您可以告诉 sort
沿二维排序。即,w.r.t.列,由
tt(k,:) = sort(t(k,:),2)
在你的另一种情况下,k
是一个整数,t(k,:)
是一个 1x4 行向量;因此,将执行 w.r.t. 排序。列。
t = magic(4);
for k = 1:4
tt(k,:) = sort(t(k,:))
end
最后,请注意@Luis Mendo:在下面的评论中的说明,我将其包含在此处以防评论被删除:
Just a clarification: by default
sort
(like most Matlab functions), doesn't work along the first dim, but along the first non-singleton dim. The distinction is important if the input matrix can be a row vector.
关于Matlab:按行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35718697/