# Matrix substitution

I'm newbie in Mathematica and would like to ask one simple question.

Let's say I have matrix with some elements == -1

mm = ConstantArray[0, {10, 10}];
mm[[4, 4]] = -1;
mm[[7, 7]] = -1;
...


Now I want to find all occurrences of -1 and set all neighbor cells around them to some values.

pos = Position[mm, -1] (* Positions are kept here *)


Now I want to surround these found positions by some values :

r1 = {{a1, a2, a3}, {a4, a5, a6}, {a7, a8, a9}};
r2 = {{b1, b2, b3}, {b4, b5, b6}, {b7, b8, b9}};
....
rr = {r1, r2, ....};


Only way I could make to work is following cycle :

For[i = 1, i <= Length[pos], i++,
mm[[(pos[[i,1]]-1);;(pos[[i,1]]+1), (pos[[i,2]]-1);;(pos[[i,2]]+1)]] = rr[[i]];
]


But it looks really ugly and I suspect would be more slow if I need to do it for bigger number of positions.

Could anyone point me to solution in more functional style ? I played a bit with ReplacePart but couldn't get it working.

-
What if -1 is on edge? – Kuba Mar 27 '14 at 23:19
Or a corner? And what if neighbors from respective -1 elements overlap? Which "neighbors" win. – ciao Mar 27 '14 at 23:20
Easy but not very efficient: Use Nearest[] – Dr. belisarius Mar 27 '14 at 23:36
Guys, thanks for the comments, that's not some 'real' piece of code - I just need an idea how to do something very close to what I showed. – mde Mar 28 '14 at 10:49

The following assumes that your replacements are 3x3 matrices but it is easy to generalize. I'm not sure if you need. It will take care of -1 on edges.

replace[mm_, reps_] := Module[{m = ArrayPad[mm, 1], pos = Position[mm, -1]},
(m[[#[[1]] ;; #[[1]] + 2, #[[2]] ;; #[[2]] + 2]] = #2) &,
{pos, reps}];

@rasher What tests? p.s. there is fp outside of scope in your module. – Kuba Mar 28 '14 at 0:57