3
$\begingroup$

Lets say there is a matrix of the form:

matrix = {{1,2,3},{4,5,6},{7,8,9}}

I want to replace the elements of the last column, if they are larger then zero, by the element itself plus RandomChoice[{0.3,0.7}->{-1,0}]

I did it this way:

matrix[[All,3]] /. x_ /; x >0 -> x+RandomChoice[{0.3,0.7}->{-1,0}]

Afterwards I swapped out the third column of the matrix by this new one.

The problem with this approach is that RandomChoice picks between -1 and 0 once, and either adds -1 to all the entries in the matrix or it adds a 0 to all the entries. But I want it to do the RandomChoice for every entry individually.

How is that possible?

$\endgroup$
2
  • 1
    $\begingroup$ I am seeing the same thing when I run your code. If I do this instead Map[If[Last[#]>0,Last[#]+RandomChoice[{0.3,0.7}->{-1,0}],Last[#]]&,matrix] then I don't get the same operation done to every element. Because there are only three items, sometimes all three do the same thing, but not always. $\endgroup$
    – Bill
    Commented Jul 23, 2023 at 22:28
  • 1
    $\begingroup$ If[#>0,#+RandomChoice[{0.3,0.7}->{-1,0}],#]&/@matrix[[All,3]] More compact, closer to your code, still works. $\endgroup$
    – Bill
    Commented Jul 24, 2023 at 0:02

3 Answers 3

8
$\begingroup$

Modify -> (Rule) to :> (RuleDelayed).

$\endgroup$
4
$\begingroup$

Also

ReplaceAt[matrix, x_/;x>0 :> x+RandomChoice[{0.3,0.7}->{-1,0}],{All,3}]

(* {{1, 2, 2}, {4, 5, 6}, {7, 8, 9}} *) 
ReplaceAt[matrix, x_/;x>0 :> x+RandomChoice[{0.3,0.7}->{-100,100}],{All,3}]

(* {{1, 2, 103}, {4, 5, 106}, {7, 8, -91}} *)

ReplaceAt[matrix, x_/;x>3 :> f[x],{All,3}]

(* {{1, 2, 3}, {4, 5, f[6]}, {7, 8, f[9]}} *)

$\endgroup$
2
$\begingroup$
m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

Using Cases

Cases[m, {a_, b_, c_ /; c > 0} :> 
 {a, b, c + RandomChoice[{0.3, 0.7} -> {-1, 0}]}]

{{1, 2, 3}, {4, 5, 5}, {7, 8, 8}}

$\endgroup$

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.