4

I'm currently learning from the wonderful post:

Where can I find examples of good Mathematica programming practice?

And i'm correcting my habits using Nest/Map/Thread instead of loops. The problem that i'm having is that i cannot find a clear/elegant expression using functional programming aproaches to do the following:

Imagine that you have a nxn matrix. I want to create a function that for each non-border entry of the matrix ( $i,j \neq 1,n$ ) the result will be the sum of all adjacent entries. For example:

$ f(A_{i,j} )= A_{i-1,j-1}+A_{i,j-1}+A_{i+1,j-1}+A_{i-1,j}+A_{i+1,j}+A_{i-1,j+1}+A_{i,j+1}+A_{i+1,j+1} $.

I'm sure that there will be thousands of elegant ways to do this. I'm really waiting to see your nice approach.

Dargor
  • 1,369
  • 9
  • 17

1 Answers1

4

You can use ListConvolve or ListCorrelate, like this:

ListConvolve[
{{1, 1, 1},
 {1, 0, 1},
 {1, 1, 1}}, mat]
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263