How to shift zero in the last column of a matrix

前端 未结 7 1504
我在风中等你
我在风中等你 2020-12-11 10:58

I have one matrix like below-

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

But I want to place all the 0 at the end of the row, s

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 11:19

    A more generic example:

    A = [1 3 0 1 1;
         0 1 1 1 2;
         0 0 1 1 3]
    
    % Sort columns directly
    [~,srtcol] = sort(A == 0,2);
    % Sorted positions 
    sz  = size(A);
    pos = bsxfun(@plus, (srtcol-1)*sz(1), (1:sz(1))'); % or use sub2ind
    

    The result

    B = A(pos)
    B =
         1     3     1     1     0
         1     1     1     2     0
         1     1     3     0     0
    

提交回复
热议问题