Delete rows with 0 for specific columns in Matlab

前端 未结 2 1848
暖寄归人
暖寄归人 2021-01-28 15:52

So I want to delete rows of a matrix that contain zero, but only for specific columns. For example:

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


        
2条回答
  •  无人及你
    2021-01-28 16:27

    You can write

    >>> secondColIsNonzero = A(:, 2) ~= 0;
    >>> fourthColIsNonzero = A(:, 4) ~= 0;
    >>> keep = secondColIsNonzero & fourthColIsNonzero;
    >>> newA = A(keep, :)
    newA =
         1     2     0     4
         1     2     3     4
         0     1     2     3
    

    to keep (i.e., not delete) columns where neither the 2nd or 4th column is zero.

    For a less verbose solution, consider indexing both columns at the same time and using all with a dimension argument:

    keep = all(A(:, [2 4]) ~= 0, 2)
    

提交回复
热议问题