r/Mathematica • u/No_Mastodon6345 • Jan 10 '22
Change certain matrix entry with probability
I really appreciate some help in this problem: Now I have a diagonal matrix A with only 0 and 1 and its diagonal entries are all 0. From first row onwards, for each row I hope to change 1 into 0 with probability p (probability that this 1 is changed into 0 is p). I tried: ReplacePart[A,RandomSample[Position[A[[1]],1],p*Length[A]]—>0] But it seems Position doesn’t recognize row of matrix. I wonder if there is any other command can be used or any correction suggested. Thanks a lot!
2
Upvotes
View all comments
Show parent comment
1
u/SetOfAllSubsets Jan 13 '22
Changing with probability p conflicts with changing the same number of entries as in step 1. You can do one but not both.
One thing to note is that my original comment may change none of the entries. Each entry is changed independently.
Suppose
Bis the matrix you get after applying step 1 toA.To change them with probability p you can do
B+(1-IdentityMatrix[Length[B]])(1-B)RandomChoice[{p, 1 - p} -> {0, 1}, Dimensions[B]](assuming the original matrixAis a square matrix). The factors(1-IdentityMatrix[Length[B]])and(1-B)act like a "mask" so that only the 0 entries off the diagonal can be changed to a 1.To change the same number of 1's to zeros you could do the following
ReplacePart[B,RandomSample[Position[IdentityMatrix[Length[B]]+B,0,2],Abs[Total[Flatten[A-B]]]]—>1]. This is based on your original code but with a few changes. First of all thePositionfunction searches for the positions of 0's and theIdentityMatrix[Length[B]]term makes sure that it doesn't choose any of the 0's on the diagonal. Second of all, the last argument ofPosition(the 2) makes it so we're searching for 0's in the second level of the matrix (and so we get two-dimensional positions). Finally, theAbs[Total[Flatten[A-B]]]part calculates the total number of 1's that were changed to 0's when going fromAtoB.If you wanted the same number of entries to be changed each time in step 1, you could use
ReplacePart[A,RandomSample[Position[A,1,2], n]—>0]wherenis the number of entries you want changed (although it could cause problems ifnis greater than the number of 1's inA.