Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

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

share|improve this question

marked as duplicate by Sjoerd C. de Vries, rm -rf Oct 12 '13 at 19:09

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 0 down vote accepted
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.

share|improve this answer
    
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? –  Nuno Calaim Oct 12 '13 at 19:29
    
@NunoCalaim please see update –  Nasser Oct 12 '13 at 19:56

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