How to perform interpolation on a 2D array in MATLAB

懵懂的女人 提交于 2019-11-27 16:10:14

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