How to perform interpolation on a 2D array in MATLAB

ぃ、小莉子 提交于 2019-11-26 17:25:23

问题


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

回答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



回答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




回答3:


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.




回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!