ReplacePart inside For loop

I am trying to replace the last column of the following expression (mat) by doing

mat = {{1, 2}, {1, 4}};
For[q = 1, q < 3, q +=1, If[mat[[q, 2]] < 3, ReplacePart[mat, {q, 2} -> -1], ReplacePart[mat, {q, 2} -> 1]];]

So I expect to get

mat = {{1, -1}, {1, 1}}

But nothing changes.
Do you have any idea why it does not work?

=================

  

 

Ivan, Mathematica questions should be asked on this site. Meta (where you originally asked this) is only for questions and discussions about this site.
– R. M.♦
Apr 19 ’13 at 22:41

=================

1 Answer
1

=================

The direct answer to your question is that you did not assign the replaced values back to the matrix mat (just add mat = ReplacePart[…] in your For loop). ReplacePart does not work like AppendTo, so you’ll have to explicitly overwrite mat.

The longer answer to your question is that For loops are almost always an inefficient way to do things in Mathematica. See this answer for a beginner’s quick-guide. An alternative way of doing the same thing:

mat = mat /. {a_?NumericQ, b_?NumericQ} :> {a, If[b < 3, -1, 1]} (* {{1, -1}, {1, 1}} *) You can even use ReplacePart in a single line: mat = ReplacePart[mat, {i_, 2} :> If[mat[[i, 2]] < 3, -1, 1]]