Add a number to each negative element of a matrix

I have the next matrix (Dimensions: {178, 178, 3}):


I want to add some quantity to each negative number of the matrix. Is it possible do that with control strucuture in Mathematica? How can I do it? thnk!




mat /. x_?Negative :> x + 5?
– kglr
Oct 15 at 21:23



related: Replace values in a list based on conditions
– WReach
Oct 15 at 22:02


2 Answers


This operation is pretty easy to do in Matheamtica. Let mat be your matrix and val your value. The you simply do

mat/. {x_ /; Negative[x] :> x + val}

If you want me to explain it just ask.

Say mat is your matrix and val is the number you wish to add to all the negative values:

mat – val Clip[Sign[mat], {-1, 0}]

Another similar method:

mat + val (1 – UnitStep[mat])



Furthermore, if mat is a packed array, it will stay packed with this method.
– Michael E2
Oct 16 at 1:47



You might give mat + Clip[mat, {0, 0}, {val, 0}] consideration, I’d imagine faster (at least on packed arrays)…
– ciao
Oct 16 at 4:32



Now I am curious. Has this solution any advatanges to a simple replace? E.g. far higher perfomance?
– meneken17
Oct 16 at 10:51