1
$\begingroup$

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

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

Mathematica graphics

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

Mathematica graphics

To answer follow up:

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]

Mathematica graphics

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

Mathematica graphics

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

| improve this answer | |
$\endgroup$
  • $\begingroup$ Variations: Replace[mat, _?(# > 15 &) -> -1], mat /. _?(# > 15 &) -> -1. $\endgroup$ – Michael E2 Oct 12 '13 at 19:16
  • $\begingroup$ 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? $\endgroup$ – gota Oct 12 '13 at 19:29
  • $\begingroup$ @NunoCalaim please see update $\endgroup$ – Nasser Oct 12 '13 at 19:56

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