# An equivalent in Mathematica [duplicate]

Let's say I have a $n$x$m$ matrix $M$ in Matlab and I want to substitute the elements of $M$ that exceed $15$ for $-1$. In Matlab I just write

M(M>15)=-1


and I'm done.

I have been struggling to do this in Mathematica. Does Mathematica have an equivalent way to do this?

Something that is easy to remember and that takes few lines will be appreciated

Thank you

mat = {{10, 20, 3}, {22, 1, -5}, {6, 15, 16}};
MatrixForm[mat]


mat = ReplacePart[mat, Position[mat, _?(#1 > 15 &)] -> -1];
MatrixForm[mat]


but what about if I want to replace those numbers that are greater than 15, smaller than 23 and are prime.

You can set the condition as you wanted, then use it:

mat = {{10, 20, 19}, {22, 18, 99}, {20, 17, 16}};
MatrixForm[mat]


cond = (15 < #1 < 23 && PrimeQ[#1]) &;
mat = ReplacePart[mat, Position[mat, _?cond] -> -1];
MatrixForm[mat]


There are other ways to do this. So, just pick one good pattern that you like and can remember and stick to it.

• Variations: Replace[mat, _?(# > 15 &) -> -1], mat /. _?(# > 15 &) -> -1. – Michael E2 Oct 12 '13 at 19:16
• Thank you, but what about if I want to replace those numbers that are greater than 15, smaller than 23 and are prime. Is there a place where I can be adding these conditions? – gota Oct 12 '13 at 19:29
• @NunoCalaim please see update – Nasser Oct 12 '13 at 19:56