我有一个如下所示的矩阵-
A=[1 1 1 1 1;
0 1 1 1 2;
0 0 1 1 3]
但是我想将所有 0
放在行的末尾,所以 A 应该像 -
A=[1 1 1 1 1;
1 1 1 2 0;
1 1 3 0 0]
我该怎么做?请Matlab专家帮助我。
最佳答案
给你。整个矩阵,无循环,甚至适用于非连续零:
A = [1 1 1 1 1; 0 1 1 1 2; 0 0 1 1 3];
At = A.'; %// It's easier to work with the transpose
[~, rows] = sort(At~=0,'descend'); %// This is the important part.
%// It sends the zeros to the end of each column
cols = repmat(1:size(At,2),size(At,1),1);
ind = sub2ind(size(At),rows(:),cols(:));
sol = repmat(NaN,size(At,1),size(At,2));
sol(:) = At(ind);
sol = sol.'; %'// undo transpose
与往常一样,对于在函数返回时不支持 ~
符号的 Matlab 版本,请将 ~
更改为虚拟变量,例如:
[nada, rows] = sort(At~=0,'descend'); %// This is the important part.
关于matlab - 如何在矩阵的最后一列中移零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18151296/