# Creating a For Loop to simulate matrix changes

I'm trying to create a For loop (Using the For syntax is a necessity for the future work I'd be performing) for a matrix given by the following lines of code:

m1 = SparseArray[_ :> RandomInteger[1], {10, 10}]; SM = UpperTriangularize[m1] + Transpose[UpperTriangularize[m1, 1]]; MatrixForm[SM]

The matrix given above is a symmetric matrix given by 0's and 1's only. I need a For loop which would do the following: A random [i,j] element is picked and is converted from either 1 -> 0 or from 0 ->1. So for example, in my 10 x 10 matrix, if [1,5] is randomly chosen, if the value started as a 1, the loop would change it to a 0. Conversely, if that value started as a 0, the loop would change it to a 1. Additionally, due to wanting to maintain the symmetry, for every [i,j] element picked, I need the corresponding [j,i] value changed as well. Lastly, each iteration needs to be building off the previous iteration. I want to be able to simulate this an infinite number of times and see how the matrix changes over performing the loop multiple times.

As mentioned above, it's a necessity that a For loop is used (even though it's sort of advised against due to other methods being more worthwhile).

• "Using the For syntax is a necessity for the future work I'd be performing" There is no problem which cannot be solved without For in Mathematica. If you disagree, give a counterexample. Commented Mar 17, 2020 at 17:11
• Recommended reading: mathematica.stackexchange.com/questions/134609/… Commented Mar 17, 2020 at 17:12
• Similar question with answers will be found by following this link Commented Mar 17, 2020 at 18:24

Perhaps something like this, very similar to https://mathematica.stackexchange.com/a/216016/148 (but concocted before I looked at that link!):

flipBit[b_] := Boole[b == 0]
SymmetricFlipBits[mat_, {i_, j_}] := Module[{m = mat},
m[[j, i]] = m[[i, j]] = flipBit[m[[i, j]]]; m]

symmetrize[mat_] :=
UpperTriangularize[mat] + Transpose[UpperTriangularize[mat, 1]]

op[symmat_] := Module[{n = Length@symmat, i, j},
i = RandomInteger[{1, n}]; j = RandomInteger[{1, n}];
SymmetricFlipBits[symmat, {i, j}]
]

m = SparseArray[_ :> RandomInteger[1], {10, 10}];
sm = symmetrize[m];

NestList[op, sm, 50]