且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在矩阵的最后一列中将零移位

更新时间:2022-12-11 21:41:18

您去了.整个矩阵,没有循环,甚至对于不连续的零也有效:

There you go. Whole matrix, no loops, works even for non-contiguous zeros:

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版本,请通过虚拟变量来更改~,例如:

As usual, for Matlab versions that do not support the ~ symbol on function return, change ~ by a dummy variable, for example:

[nada, rows] = sort(At~=0,'descend'); %// This is the important part.