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
array A
. I need to inter
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
Have you seen the interp2
function?
From MatLab documentation:
ZI = interp2(X,Y,Z,XI,YI)
returns matrix ZI
containing elements corresponding to the elements of XI
and YI
and determined by interpolation within the two-dimensional function specified by matrices X
, Y
, and Z
. X
and Y
must be monotonic, and have the same format ("plaid") as if they were produced by meshgrid
. Matrices X
and Y
specify the points at which the data Z
is given. Out of range values are returned as NaN
s.
Use the spline()
command like this:
% A contains N rows and 2 columns
pp = spline(A(:,1), A(:,2));
ppval(pp,3.44)
ans =
0.4454
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