I'm trying to write a code where each matrix element swaps with a randomly selected neighbor (cardinal directions only) to redistribute the matrix. So far I've been able to replace an element with its neighbor, making the elements twins, but I want to preserve the relative amount of "-1"s to "1"s. What you see below is what I have currently, which shows how I identify the neighbors of each element, and how I randomize which one switches with it. The output of this process gives me something in the form of {i,j}
, which means I can't use Si[[choice]]
, because that would be effectively saying Si[[{i,j}]]
, which isn't correct syntax.
I'm pretty new to Mathematica, so any help would be greatly appreciated! :)
Input:
Si = {{-1, -1, -1}, {1, -1, -1}, {-1, 1, -1}};
Off[General::stop];
ii = 3;
jj = 3;
For[i = 1, i <= ii, i++,
For[j = 1, j <= jj, j++,
choices = {{i, Mod[j - 1, ii, 1]}, {Mod[i - 1, ii, 1], j},
{i, Mod[j + 1, ii, 1]}, {Mod[j - 1, ii, 1], j}};(*identifies neighbors*)
choice = choices[[RandomInteger[{1, 4}]]]; (*randomly chooses a neighbor*)
Si[[i, j]] = choice;(****************)
Print[choices];
Print[choice];
Print[Si]
]
]
Output:
{{1,3},{3,1},{1,2},{3,1}}
{3,1}
{{{3, 1}, -1, -1}, {1, -1, -1}, {-1, 1, -1}}
{{1,1},{3,2},{1,3},{1,2}}
{1,2}
{{{3, 1}, {1, 2}, -1}, {1, -1, -1}, {-1, 1, -1}},
etc. and so forth.
Okay, so if I replace
Si[[i, j]] = choice;
with
Si[[i, j]] = Extract[Si, choice];
I can get the output to have replaced my original element, but I still don't know how to replace the neighbor with the value of the original element then.