# Using Map in a function definition

I want to calculate the hessian of a matrix. So each element gets replaced by a 2 by 2 matrix.

hessian[im_, s_] :=
{{gD[im, 2, 0, 2], gD[im, 1, 1, 2]}, {gD[im, 1, 1, 2], gD[im, 0, 2, 2]}};


Now im = My matrix.

I want to modify my hessian function in some way (using Map) such that when I calculate the hessian of im, 1 element at a time is calculated by gD. At this time gD works on the entire im matrix.

How do I do this? Any help (preferable code) will be very helpful. I am new to Mathematica, struggling, and very frustrated.

-
More details on the definition of gD or a simple example with data might be helpful. Also this implementation may help you. Or are you just looking for something like hessian[im_, s_] := {{gD[#, 2, 0, 2], gD[#, 1, 1, 2]}, {gD[#, 1, 1, 2], gD[#, 0, 2, 2]}}&/@im; – Karsten 7. Jul 15 '14 at 16:16

This might be what you're after (although some more details would indeed help):

hessian[im_] := Map[
{
{gD[#, 2, 0, 2], gD[#, 1, 1, 2]},
{gD[#, 1, 1, 2], gD[#, 0, 2, 2]}
} &,
im,
{2}
];


This is almost Karsten's suggestion, the difference being the third argument to Map, {2}. It tells Map to only map on elements at level 2 of the input expression. Here it is in action on a generic 2x2 matrix:

hessian[ Array[m, {2, 2}] ] // MatrixForm


-