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.

  • 1
    $\begingroup$ Hi, take a look at ListConvolve. $\endgroup$ – Kuba Feb 12 '15 at 14:37

You can use ListConvolve or ListCorrelate, like this:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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