Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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
up vote 6 down vote accepted

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]]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.