Delete rows with 0 for specific columns in Matlab

前端 未结 2 1847
暖寄归人
暖寄归人 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)
    
    0 讨论(0)
  • This is easily solved using the find() function:

    B = A(find(A(:,2)~=0),:)
    

    find() by default returns rows, so calling it in this case returns the index of the rows where the value on the second column is not 0.

    0 讨论(0)
提交回复
热议问题