1
$\begingroup$

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

{{-1.22,2.44,3.14},{1.22,0.54,0.01},{1.21,-0.14,-2.31},{0.21,1.24,-0.42},...,{1.24,-0.25,1.34},{3.14,-3.14,-2.89}}

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!

$\endgroup$
2

2 Answers 2

2
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ The problem with this is that it won't work if the elements are symbolic expressions rather than numbers. How could that be modified to make it work in that case as well? $\endgroup$ Commented Jan 10, 2019 at 15:13
4
$\begingroup$

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])
$\endgroup$
3
  • $\begingroup$ Furthermore, if mat is a packed array, it will stay packed with this method. $\endgroup$
    – Michael E2
    Commented Oct 16, 2016 at 1:47
  • 2
    $\begingroup$ You might give mat + Clip[mat, {0, 0}, {val, 0}] consideration, I'd imagine faster (at least on packed arrays)... $\endgroup$
    – ciao
    Commented Oct 16, 2016 at 4:32
  • $\begingroup$ Now I am curious. Has this solution any advatanges to a simple replace? E.g. far higher perfomance? $\endgroup$
    – meneken17
    Commented Oct 16, 2016 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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