I am doing some numerical computations and a few iterations return values that are obviously incorrect (some numerical integration problem, I suppose.). I have managed to set these values to zero but this does not goes well with the ListLinePlot I'm making. So, given this context, my problem is the following:

I have a nX2 matrix where n is a fairly large number. A few elements in column 2 are zero and I want to delete them. If there was only one zero element I would identify the position j of the zero and use Delete[matrix,j]. Since I have more than one of these I've been using

For[j = 1, j <= Length[matrix], j = j + 1, 
If[matrix[[j, 2]] == 0, matrix = Delete[matrix, j]]

The problem is that this routine only deletes the few first lines with zeros and then stop doing that. I imagine it has something to do with Length[matrix] being changed, but I'm not sure. Could ou help me, please?

Thank you very much.

  • 2
    $\begingroup$ Have you tried Select? Select[matrix, #[[2]] != 0 &] $\endgroup$
    – BlacKow
    May 9, 2016 at 16:53
  • 2
    $\begingroup$ ...or Cases[]? $\endgroup$ May 9, 2016 at 16:54
  • 2
    $\begingroup$ ... or DeleteCases[mat, {_, 0}] or Pick[mat, Unitize[mat[[;; , 2]]], 1]? $\endgroup$
    – kglr
    May 9, 2016 at 17:01
  • $\begingroup$ Thank you so much. Select worked like a charm. Could you help me, though, to understand the syntax? What are the roles of # and &? Thank you very much. $\endgroup$
    – Gabu
    May 9, 2016 at 17:49
  • $\begingroup$ @Gabu Take a look at this post. The #& is slot/pure function notation. A slot is unnamed argument. $\endgroup$
    – BlacKow
    May 9, 2016 at 18:03


Browse other questions tagged or ask your own question.