I have a matrix where I would like to look for all elements around element x (in this example -2) and replace all the ones that are 0 with the number 1.
My matrix (matrix0
) looks as follows:
\begin{array}{cccccccccc} -1 & -1 & -1 & -1 & -1 & -1 & -1 & -1 & -1 & -1 \\ -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -2 \\ -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\ -1 & -1 & -1 & -1 & -1 & -1 & -1 & -1 & -1 & -1 \\ \end{array}
matrix0 = {{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, -2},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}};
I wrote a module, which gives me the positions of the elements around my x like this:
Clear[around] (* The following module gives a list of all positions next to that of x0
in matrix mat0 *)
around[x0_, mat0_] :=
Module[{x, mat, pos},
x = x0;
mat = mat0;
pos[x_] := Flatten[Position[mat, x]];
Cases[Tuples[Range[Dimensions[mat][[1]]],
2], {a_,
b_} /; (a == pos[x][[1]] &&
b == pos[x][[2]] - 1) || (a == pos[x][[1]] - 1 &&
b == pos[x][[2]]) || (a == pos[x][[1]] - 1 &&
b == pos[x][[2]] - 1) || (a == pos[x][[1]] + 1 &&
b == pos[x][[2]] - 1) || (a == pos[x][[1]] - 1 &&
b == pos[x][[2]] + 1) || (a == pos[x][[1]] &&
b == pos[x][[2]] + 1) || (a == pos[x][[1]] + 1 &&
b == pos[x][[2]]) || (a == pos[x][[1]] + 1 &&
b == pos[x][[2]] + 1)]
]
For -2 this yields the result:
around[-2, matrix0]
{{4,9},{4,10},{5,9},{6,9},{6,10}}
I now tried to let all of these elements which are 0 be replaced by 1, however Mathematica is only giving me a Null
output. Any ideas why this doesn't work?
For[i=1,i<=Length[around[-2,matrix0]],i++,
If[Part[matrix0,around[-2,matrix0][[i,1]],around[-2,matrix0][[i,2]]]==0,
ReplacePart[matrix0,around[-2,matrix0][[i]]->1],Null]]
EDIT: These answers are already helping me learn new functions thank you. However my question mainly was why my version does not work seeing as I can't find an illogical step in it. The reason my version is so unnecessarily complicated is partly because I am a Mathematica beginner but also because I want to generalise this method to build up my matrix. After having changed the 0s around -2 to 1s, I would like to change the 0s around all 1s to 2s and the 0s around all 2s to 3s and so on. Any suggestion what I should look into to solve this on my own? Or is my approach just fundamentally doomed to failure?
{m, n} = Dimensions[mat0]; ReplacePart[mat0, Cases[First[Position[mat0, x0]] + # & /@ DeleteCases[Tuples[{-1, 0, 1}, 2], {0, 0}], {j_, k_} /; 1 <= j <= m && 1 <= k <= n] -> 1]
. $\endgroup$