# Interpolating 2D data [duplicate]

Possible Duplicate:
Interpolating 2D data with missing values

I am trying to interpolate a 21x21 array of values. The 21x21 array sometimes has zero values and with the help of interpolation, I am replacing the zero with an appropriate value to get a reasonable output.

My code is as follows:

binmeans
dataInt = Flatten[binmeans]

int = Interpolation[Select[Transpose[{Range[Length[dataInt]], dataInt}],
Last[#] != 0 &], InterpolationOrder -> 1]

l = 1;
gTable1 = Table[0, {binSize}, {binSize}];
For[x = 1, x <= binSize, x++,
For [y = 1, y <= binSize, y++,
gTable1[[x, y]] = int[l];
l++]
]


I flatten the binmeans list, selected the values which are not zero, made an interpolation function, create another 21x21 table and populate it with the output of the interpolation function.

The final output is as follows: And the expected output is this : The Interpolation function works by interpolating values on the x-axis only. I am wondering how can I interpolate by considering all the points in the surrounding (x and y axis interpolation). Thank you

• This is exactly the same question you asked here. When you have further question or don't understand an answer completely, why don't you comment under the answer? – halirutan Jan 31 '13 at 4:44

The problem with your code is that when you remove the zeros your data becomes unaligned. A simple case would be the matrix with {1,2} on the diagonal and zeros elsewhere, then you'd just be interpolating {1,2} and that will extrapolated to {1,2,3,4} and be completely unaligned with the {1,0,0,2} that you compare it to.

By using the Interpolation specification of the form: {{{x1,y1,...},f1},{{x2,y2,...},f2},...} you can interpolate the 2D data directly:

n = 30;
dat = Array[(#1 - n/2)^2 + (#2 - n/2)^2 &, {n, n}];

f = Interpolation[Flatten[Array[{ {#1, #2}, dat[[#1, #2]]} &, {n, n}], 1]]
res = Array[f[#1, #2] &, {n, n}];
Max[Abs[dat - res]] (* 0 *)
DensityPlot[f[x, y], {x, 1, 30}, {y, 1, 30}] Since you don't want the zeros you can do something like:

ipdat = DeleteCases[
Flatten[Array[{{#1, #2}, dat[[#1, #2]]} &, {n, n}], 1]
, _?(PossibleZeroQ[Last@#] &)];
g = Interpolation[ipdat]
{g[n/2,n/2],f[n/2,n/2]} (* {1,0} *)

• many thanks for the answer. It works fine. However, some of the interpolated values are sometimes very different to its surrounding values. And I would like to know to smooth out all the values in the array? Any ideas. Thanks! – Mun Feb 1 '13 at 0:40
• @Mun could replace a zero with mean-of-all-surrounding-values perhaps – ssch Feb 1 '13 at 23:57
• ,Can you please suggest how can I replace the zero with mean of surrounding values. It's a good idea, but is there any function to do that? Can interpolation function be tweaked to do it? Thanks – Mun Feb 5 '13 at 4:01
• @Mun when do the interpolated values become very different? Got some small example? – ssch Feb 5 '13 at 10:58