Say I have a matrix of:

tmp1 = 5;
tmp2 = 5;
tmp3 = RandomChoice[{0, 1, 2, 3, 4, 5}, {tmp1, tmp2}];

How to do a conditional operation of elements - 1 if non-zero, else do nothing, as in the attached:enter image description here. Maybe using Positive?

  • $\begingroup$ tmp3 /. (x_ ?Positive -> x - 1)? $\endgroup$ – b.gates.you.know.what Nov 13 '12 at 15:14
  • $\begingroup$ tmp3 /. x_?Positive :> x - 1 or tmp3 - Boole[Positive[tmp3]] then? $\endgroup$ – J. M. will be back soon Nov 13 '12 at 15:17
  • $\begingroup$ Hi @b.gatessucks and J.M thanks you are very helpful. $\endgroup$ – sebastian c. Nov 13 '12 at 15:20
  • 2
    $\begingroup$ Sebastian, I notice you haven't yet accepted any answers to questions you have asked. You can help yourself, future users, and this site as a whole, by following the guidance in the faq: "As you see new answers to your question, vote up the helpful ones by clicking the upward pointing arrow to the left of the answer. ... When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer." $\endgroup$ – whuber Nov 13 '12 at 18:48
  • $\begingroup$ Hi @whuber Thanks. $\endgroup$ – sebastian c. Nov 15 '12 at 0:12

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:

  • $\begingroup$ You probably want Abs@Sign@tmp3, which is the same as Unitize. $\endgroup$ – rm -rf Nov 13 '12 at 16:12
  • $\begingroup$ OPs matrix is all positive integers, so it's the same. But it is not clear what the desired behavior would be if you had negative integers: using Sign[ ] they would all head towards zero; using Unitize the negatives would keep decreasing. $\endgroup$ – bill s Nov 13 '12 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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