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
vq = interp1( x , v , xq ) returns interpolated values of a 1-D function at specific query points using linear interpolation. Vector x contains the sample points, and v contains the corresponding values, v(x). Vector xq contains the coordinates of the query points.
Know the formula for the linear interpolation process. The formula is y = y1 + ((x – x1) / (x2 – x1)) * (y2 – y1), where x is the known value, y is the unknown value, x1 and y1 are the coordinates that are below the known x value, and x2 and y2 are the coordinates that are above the x value.
For interp2 , the full grid is a pair of matrices whose elements represent a grid of points over a rectangular region. One matrix contains the x-coordinates, and the other matrix contains the y-coordinates. The values in the x-matrix are strictly monotonic and increasing along the rows.
Accepted Answer The query points are the points where you want to know the value. You can also have a look at the examples that are given in the doc.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With