Say I have a matrix of:
tmp1 = 5;
tmp2 = 5;
tmp3 = RandomChoice[{0, 1, 2, 3, 4, 5}, {tmp1, tmp2}];
MatrixForm[tmp3]
How to do a conditional operation of elements - 1 if non-zero, else do nothing, as in the attached:. Maybe using Positive?
Say I have a matrix of:
tmp1 = 5;
tmp2 = 5;
tmp3 = RandomChoice[{0, 1, 2, 3, 4, 5}, {tmp1, tmp2}];
MatrixForm[tmp3]
How to do a conditional operation of elements - 1 if non-zero, else do nothing, as in the attached:. Maybe using Positive?
You have lots of options. Among them Replace
:
Replace[tmp3, x : Except[0] :> x - 1, {2}]
And numerically for the entire matrix:
tmp3 - Unitize[tmp3]
Another possibility is to use Sign[]. To make each positive element of the matrix decrease by one:
tmp3-Sign[tmp3]
Abs@Sign@tmp3
, which is the same as Unitize
.
$\endgroup$
– rm -rf♦
Nov 13 '12 at 16:12
tmp3 /. (x_ ?Positive -> x - 1)
? $\endgroup$ – b.gates.you.know.what Nov 13 '12 at 15:14tmp3 /. x_?Positive :> x - 1
ortmp3 - Boole[Positive[tmp3]]
then? $\endgroup$ – J. M. will be back soon♦ Nov 13 '12 at 15:17