折叠/压缩矩阵,向左移动非零元素

时间:2017-03-20 05:52:45

标签: arrays matlab compression reshape

我正在尝试折叠数组,以便满足以下示例

v = [ 1 2 3; 0 0 1; 0 1 0]

会将所有非零元素向上推到左边,这样我就会留下

v = [1 2 3; 0 1 1;]

我需要满足的另一个案例是

v2 = [1 2 3; 1 0 0; 1 0 0; 0 1 0]

变为

v2 = [1 2 3; 1 1 0; 1 0 0]

所以基本上我通过将所有非零值推到相应列的左边来挤压矩阵。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

这是一个可以重现你的例子的函数。有关详细信息,请参阅注释

pushmatrixup(v)

ans =
 1     2     3
 0     1     1
 0     0     0


pushmatrixup(v2)

ans =
 1     2     3
 1     1     0
 1     0     0
 0     0     0   

检查:

sort

编辑:如果非零值总是大于,那么您只需使用sort(v2, 'descend') ...

pushmatrixup

第二部分是删除底部的全零行。扩展sort功能,或在function A = pushmatrixup(A) % Loop over each column of matrix A for col = 1:size(A,2) % Rearrange the values in column 'col', with the logic: % [Values in column 'col' which don't equal 0; % Values in column 'col' which do equal 0] A(:,col) = [A(A(:,col) ~= 0, col); A(A(:,col) == 0, col)]; end % All columns now have their 0s 'sunk' to the bottom of the column. % Remove the all-zero rows % Loop from bottom to top on rows until one has a non-zero value for rw = size(A,1):-1:1 if any(A(rw,:) ~= 0) % Break if non-zero element found in row break end end % rw is row number of row with all zero elements, as loop was % broken when this condition was broken. Cut A off at row rw. A = A(1:rw,:); end ...

之后执行此操作
http://example.com/controller/action?language=en&page=8