Search code examples
matlabdependenciesdelete-row

Delete values from different columns depending on a value from a specific column


I have a double variable with 3 columns. Sometimes, in the second column I obtain the value zero. In case it happens I want to completely erase that line. For instance:

12346 67 89

1245 0 765

56 0 99

19862 8 675

What I would like to get:

12346 67 89

19862 8 675

Thanks in advance for your help.


Solution

  • This is generally done using logical indexing:

    A = [12346 67 89
         1245  0  765
         56    0  99
         19862 8  675];
    
    mask = (A(:,2) ~= 0);
    ans = A(mask, :)
    

    The same but by deleting elements from the original array:

    mask = (A(:,2) == 0);
    A(mask, :) = []
    

    A very similar question: How can you remove matrix rows in Matlab based on some criteria?