I have a list (21 x 21) containing values. I want to eliminate slots containing zeros by interpolating the nearest values and overwriting the zeros. How do I use the Mathematica's ListInterpolation
function to do that?
Answer
You have to use Interpolation
because there it is possible to give values which do not lie on a structured grid. Let's create some test data which has zeroes in it
data = Table[ Sin[x] + Cos[y], {x, 0, Pi/2, Pi/2/29.}, {y, 0, Pi/2, Pi/2/29.}]*
RandomInteger[{0, 1}, {30, 30}];
ListPlot3D[data]
Now you attach the position of every value to it so you get tuples of the form {{x,y},value}
and Select
only those, where value
is not zero. This can then be interpolated
data2 = Select[Flatten[MapIndexed[{#2, #1} &, data, {2}], 1],
Last[#] != 0 &];
ip = Interpolation[data2];
Plot3D[ip[y, x], {x, 1, 30}, {y, 1, 30}]
Note, that with such data you always have an InterpolationOrder
of 1.
Update regarding your comment
Yes, this is indeed a problem and you have to decide what to do. First you have to understand the issue. Let's assume the following grid with values, where all white cells are zero and have to be interpolated
When you look at cell {3,1}
, you see that such a situation is not a problem, because the value can be interpolated since it is place in between the cells {1,2}
and {1,4}
.
On the other hand, the cell {5,5}
is a problem, because no surrounding cells with values are left which can be used for interpolation. Therefore, what you have to ensure is, that you have values on all 4 corners of your matrix. When they got selected out because they were zero, then you have to fill them with values. When they are indeed zero, and got kicked out accidentally, then you have to fill them back in.
You can ignore the corners when you Select
non-zero values by changing the condition in the end
{ny, nx} = Dimensions[data];
data2 = Select[Flatten[MapIndexed[{N@#2, #1} &, data, {2}], 1],
Last[#] != 0 &&
(First[#] =!= {1, 1} || First[#] =!= {1, nx} ||
First[#] =!= {ny, 1} || First[#] =!= {ny, nx}) &];
Comments
Post a Comment