Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
What if -1 is on edge? –  Kuba Mar 27 at 23:19
Or a corner? And what if neighbors from respective -1 elements overlap? Which "neighbors" win. –  rasher Mar 27 at 23:20
Easy but not very efficient: Use Nearest[] –  belisarius Mar 27 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 at 10:49

1 Answer 1

up vote 2 down vote accepted

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}];
  ArrayPad[m, -1]]

mm = ConstantArray[0, {10, 10}];
mm[[1, 1]] = -1;
mm[[7, 7]] = -1;
replace[mm, rr] // MatrixForm

enter image description here

share|improve this answer
Nice and clean. +1 –  rasher Mar 28 at 0:53
@rasher What tests? p.s. there is fp outside of scope in your module. –  Kuba Mar 28 at 0:57
never mind re: blow-up, had junk in symbols from testing OP... DOH –  rasher Mar 28 at 0:58
@rasher oh, ok :) –  Kuba Mar 28 at 0:59
Excellent, it's exactly what I need ! Edges and corners are not being considered here bcouse it's not real code. –  mde Mar 28 at 10:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.