Matlab flipped 2d interp2 interp2
I have a function V that is calculated from two inputs (X, Y). Since the computation is quite demanding, I am just doing it on a grid of points and would like to rely on 2d linear interpolation. Now I want to reverse this function for a fixed Y. So basically my starting point is:
X = [1,2,3];
Y = [1,2,3];
V =[3,4,5;6,7,8;9,10,11];
Of course, it's easy to get V in any combination (X, Y), for example:
Vq = interp2(X,Y,V,1.8,2.5)
gives
Vq = 8.3000
But how would one find X for given V and Y using 2d linear interpolation? I will have to do this task many times, so I need a quick and easy solution.
Thank you for your help, your efforts are greatly appreciated.
R.
source to share
EDIT using additional information
If you do not find both x and y, but one of them is given, this problem is reduced to finding the minimum in only 1 direction (i.e. in the x direction). A simple approach formulates this in a problem that can be minimized by an optimization procedure such as fminsearch
. Therefore, we define a function f
that returns the difference between the value Vq
and the result of the interpolation. We try to find x
one that minimizes this difference after we make an intuitive guess x0
. Depending on this initial assumption, the result will be what we are looking for:
% Which x value to choose if yq and Vq are fixed? xq = 1.8; % // <-- this one is to be found yq = 2.5; % // (given) Vq = interp2(X,Y,V,xq,yq); % // 8.3 (given) % this function will be minimized (difference between Vq and the result % of the interpolation) f = @(x) abs(Vq-interp2(X, Y, V, x, yq)); x0 = 1; % initial guess) x_opt = fminsearch(f, x0) % // solution found: 1.8
source to share
Nras, thank you very much. In the meantime, I did something else:
function [G_inv] = G_inverse (lambda,U,grid_G_inverse,range_x,range_lambda)
for t = 1:size(U,1)
for i = 1:size(U,2)
xf = linspace(range_x(1), range_x(end),10000);
[Xf,Yf] = meshgrid(xf,lambda);
grid_fine = interp2(range_x,range_lambda,grid_G_inverse',Xf,Yf);
idx = find (abs(grid_fine-U(t,i))== min(min(abs(grid_fine-U(t,i))))); % find min distance point and take x index
G_inv(t,i)=xf(idx(1));
end
end
G_inv should contain x, U - yq in the above example, and grid_G_inverse contains Vq. range_x and range_lambda are the corresponding vectors for the grid axis. What do you think of this decision, also compared to yours? I would suggest mine is faster but less accurate. Spped is, however, a serious problem in my code.
source to share