matlab - 如何在矩阵的最后一列中移零

标签 matlab

我有一个如下所示的矩阵-

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/

相关文章:

matlab - 在matlab中将范围划分为垃圾箱

python - Python 的 Matlab findpeaks 算法

matlab - 如何将目录转换为包?

matlab - 我如何为一段 Matlab 数字代码构建完整的 UI?

matlab - 最小均方均衡光纤 channel

image - 在 MATLAB 中将两个 y 轴放在 imagesc 图像上

arrays - 在 3d 矩阵的第二维中排序

python - 为什么 Python 中的 CNN 比 Matlab 中的表现差很多?

matlab - 打开新图像时如何在 Matlab 轴窗口中保留文本对象?

MATLAB:计算时间序列每 1 分钟间隔的平均值