# Replace a column/row of a matrix under a condition by a random number

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?

• 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.
– Bill
Commented Jul 23, 2023 at 22:28
• If[#>0,#+RandomChoice[{0.3,0.7}->{-1,0}],#]&/@matrix[[All,3]] More compact, closer to your code, still works.
– Bill
Commented Jul 24, 2023 at 0:02

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

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]}} *)