How to rewrite a function in a more compact and generalized way?

Consider a function as

sum1:= {-1, 1} #[[1, 1]] + {0, 1} #[[1, 2]] + {1, 1} #[[1, 3]] +
{-1, 0} #[[2, 1]] + {0, 0} #[[2, 2]] + {1, 0} #[[2, 3]] +
{-1, -1} #[[3, 1]] + {0, -1} #[[3, 2]] + {1, -1} #[[3, 3]] &

I wish to write it in the following way,

sum2:= Module[{pos, val},
pos = Table[{i, j}, {i, -1, 1, 1}, {j, -1, 1, 1}];
val = Map[Table[#[[i, j]], {i, 1, 3, 1}, {j, 1, 3, 1}] &];
pos val];

However, it's not giving me the desired output as

{-1, 1} #1[[1, 1]] + {0, 1} #1[[1, 2]] + {1, 1} #1[[1, 3]] + {-1, 0} #1[[2, 1]] + {0, 0} #1[[2, 2]] + {1, 0} #1[[2, 3]] + {-1, -1} #1[[3, 1]] + {0, -1} #1[[3, 2]] + {1, -1} #1[[3, 3]] &

How can I modify sum2 to get the desired result?

• Do you want to generate the function for later use or to write sum1 procedure in a more generalized way? Close but not the same so I'm asking. – Kuba Feb 21 '18 at 21:38
• @Kuba I want both. Using # I want it to be used for a later purpose. In addition, I want to generalize it to be applied on 3D matrix as well. – Majis Feb 22 '18 at 10:39
• What I meant is, do you want sum2 to return (...)& so a Function[...] or do you want sum2[input] to return whatever (...)& @ input would return. Very similar but different, see Alan's answer, he does not create an intermediate function but works directly with input (mat33). – Kuba Feb 22 '18 at 11:52
• @Kuba I want the first one you've mentioned. – Majis Feb 22 '18 at 12:03
• Ok, thanks for the update. – Kuba Feb 22 '18 at 12:17

We can use dummy foo/bar symbols instead of Part and List to prevent missing part error and an automatic threading for {a,b} c.

sum2 = Module[{pos, val, bar, foo}
, pos = Catenate @ Transpose @ Table[foo[i, j], {i, -1, 1}, {j, 1, -1, -1}]
; val = Catenate@Table[bar[#, i, j], {i, 3}, {j, 3}]
; Function[Evaluate[pos.val]] /. {foo -> List, bar -> Part}
]
#1[[3, 1]] {-1, -1} + #1[[2, 1]] {-1, 0} + #1[[1, 1]] {-1, 1} + #1[[3,
2]] {0, -1} + #1[[2, 2]] {0, 0} + #1[[1, 2]] {0, 1} + #1[[3,
3]] {1, -1} + #1[[2, 3]] {1, 0} + #1[[1, 3]] {1, 1} &
• Another way to write pos.val is Tr@(Array[part, {3, 3}].Array[list, {3, 3}, {{-1, 1}, {1, -1}}]) which maybe useful for the OP. – SquareOne Feb 22 '18 at 14:21
sum3[mat33_?MatrixQ] := With[{
pos = Reverse /@ Tuples[{-Range[-1, 1], Range[-1, 1]}],
val = Extract[mat33, Tuples[Range, 2]]
},
Total[pos*val]
]

Or, letting mA be your 3-by-3 matrix, you could just Total[mA*Outer[{#2, #1} &, {1, 0, -1}, {-1, 0, 1}], 2].

• What is mA in the second part? – Majis Feb 22 '18 at 10:27
• @Majis It's your 3 x 3 matrix. – Alan Feb 22 '18 at 13:14