Functional programming approach to avoid traditional loops

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.

• Hi, take a look at ListConvolve. – Kuba Feb 12 '15 at 14:37

You can use ListConvolve or ListCorrelate, like this:

ListConvolve[
{{1, 1, 1},
{1, 0, 1},
{1, 1, 1}}, mat]

• And in the case that the function is not Plus? For example, times? – Dargor Feb 12 '15 at 15:30
• @PabloGalindoSalgado Did you check the documentation links I posted? The answer is right there. – Szabolcs Feb 12 '15 at 15:39
• Oh, you are right. So so sorry. Thank you so much! – Dargor Feb 12 '15 at 15:45