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 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 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 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
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 NaNs.
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 来源:https://stackoverflow.com/questions/16346684/how-to-perform-interpolation-on-a-2d-array-in-matlab