How to perform interpolation on a 2D array in MATLAB
46,832
Solution 1
For data on a regular grid, use interp2. If your data is scattered, use griddata. You can create an anonymous function as a simplified wrapper around those calls.
M = 10;
N = 5;
A = rand(M,N);
interpolatedA = @(y,x) interp2(1:N,1:M,A,x,y);
%interpolatedA = @(y,x) griddata(1:N,1:M,A,x,y); % alternative
interpolatedA(3.3,8.2)
ans =
0.53955
Solution 2
Here is an example using scatteredInterpolant
:
%# get some 2D matrix, and plot as surface
A = peaks(15);
subplot(121), surf(A)
%# create interpolant
[X,Y] = meshgrid(1:size(A,2), 1:size(A,1));
F = scatteredInterpolant(X(:), Y(:), A(:), 'linear');
%# interpolate over a finer grid
[U,V] = meshgrid(linspace(1,size(A,2),50), linspace(1,size(A,1),50));
subplot(122), surf(U,V, F(U,V))
Note that you can evaluate the interpolant object at any point:
>> F(3.14,3.41)
ans =
0.036288
the above example uses a vectorized call to interpolate at all points of the grid
Comments
-
MaxPY over 4 years
How can I make a function of 2 variables and given a 2D array, it would return an interpolated value?
I have
N x M
arrayA
. I need to interpolate it and somehow obtain the function of that surface so I could pick values on not-integer arguments. (I need to use that interpolation as a function of 2 variables)For example:
A[N,M] //my array // here is the method I'm looking for. Returns function interpolatedA interpolatedA(3.14,344.1) //That function returns interpolated value
-
MaxPY about 11 yearsThanks, but I think that's not what I need. As far as I see, using those functions, I can only create another array with surface values. But I need to use interpolation of an array as a function. (I've edited the question)
-
MaxPY about 11 yearsThanks, but I think that's not what I need. As far as I see, using those functions, I can only create another array with surface values. But I need to use interpolation of an array as a function. (I've edited the question)
-
shoelzer about 11 years@Max You can use these functions to interpolate any number of points. You can get one value at the specific [x,y] that you want.
-
MaxPY about 11 yearsThanks! That was easy one, I should've guessed myself. I'm kinda newbie yet, sorry :)
-
geometrikal over 7 yearsJust a note: x and y values correspond to
column
androw
not the other way around. Sointerpolated(3.3,8.2)
is returning a value in the region ofA(8,3)
-
shoelzer over 7 years@geometrikal Thanks! I updated the anonymous function so inputs are ordered (y,x) just like array indexing.