# Interpolating a function of two variables

I am trying to create the interpolating function for a function of two variables, over a finite area. Just for consistency we can think of a function:

MyFunc[a_,b_]:=Sin[a*b]/Sqrt[1+a^2+b^2]


I've read the documentation and, in order to get the interpolating function I use:

MyTable=Table[MyFunc[a,b],{a, -5, 5, 0.1}, {b, -5, 5, 0.1}]
MyApproximateFunc = ListInterpolation[MyTable]


this seem to work, but when I try to plot MyFunc and MyApproximateFunc they look very different: I must have missed some detail...

Plot3D[MyFunc[a, b], {a, -5, 5}, {b, -5, 5}]
Plot3D[MyApproximateFunc[a, b], {a, -5, 5}, {b, -5, 5}]


• its because your MyTable does not know about the corresponding values of a and b; try MyTable = Table[{a, b, MyFunc[a, b]}, {a, -5, 5, 0.1}, {b, -5, 5, 0.1}] // Flatten[#, 1] &; MyApproximateFunc = Interpolation[MyTable] Nov 5, 2012 at 17:34
• If you read the docs, notice that ListInterpolation[] supports a domain specification; try MyApproximateFunc = ListInterpolation[MyTable, {{-5, 5}, {-5, 5}}]. Nov 5, 2012 at 17:40
• chris: works like a charm! Too bad it's only a comment and I can't accept it... :-)
– zakk
Nov 5, 2012 at 17:41
• @zakk you can always upvote my comment ;-) Nov 5, 2012 at 18:40
• C'mon @chris move your comment to an answer, I promise I won't tell. Nov 5, 2012 at 19:13

OK then after Sjoerd C. de Vries request ;-), you can either use (less thinking)

MyTable = Table[{a, b, MyFunc[a, b]}, {a, -5, 5, 0.1}, {b, -5, 5, 0.1}] // Flatten[#, 1] &;
MyApproximateFunc = Interpolation[MyTable];


or (from @J.M.'s comment, less memory)

 MyTable = Table[MyFunc[a, b], {a, -5, 5, 0.1}, {b, -5, 5, 0.1}] // Flatten[#, 1] &;
MyApproximateFunc = ListInterpolation[MyTable, {{-5, 5}, {-5, 5}}];


to get

  GraphicsRow[{Plot3D[MyFunc[a, b], {a, -5, 5}, {b, -5, 5}],
Plot3D[MyApproximateFunc[a, b], {a, -5, 5}, {b, -5, 5}]}]


Another possibility is FunctionInterpolation. Straight from the Documentation:

   MyApproximateFunc =
FunctionInterpolation[
Evaluate[Table[D[MyFunc[a, b], {{a, b}, k}], {k, 0, 2}]], {a, -5,
5}, {b, -5, 5}]


We have to provide derivatives to get a better interpolation.

GraphicsRow[{Plot3D[MyFunc[a, b], {a, -5, 5}, {b, -5, 5}],
Plot3D[MyApproximateFunc[a, b], {a, -5, 5}, {b, -5, 5}]}]


• @Markus.Roellig ah! I knew that there was a way to tell interpolation to use the derivative as well. Thanks for the tip! Nov 6, 2012 at 20:54