0

I have a set of data and would like to use linear interpolation in Matlab to find the corresponding value of a specific point.

x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
vq1 = interp1(x,y,xq);
plot(x,y,'o',xq,vq1,':.');

After doing this, is there any way for me to find the value of x given a value of y? For example, when y = 3.5, x = ?

TYL
  • 1,577
  • 20
  • 33

2 Answers2

2

Simple Interpolation

You could just interpolate the other way...

% Your code
x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
yq = interp1(x, y, xq);

% Interpolate your newly interpolated xq and yq to find x = x1 when y = 3.5
x1 = interp1(yq, xq, 3.5)

Finding Zeros

This approach is more complicated but, depending on your data, may be more applicable.

You could use some sort of root finding approach using fzero, and a function defined as below

% Initialise
x = [1 2 3 4 5 6 7 8 9]; y = [1 2 3 4 5 4 2 6 8];
% Define function, like your interpolation, which will have a zero at x=x0
% when y = y0. 
y0 = 3.5;
yq = @(xq) interp1(x, y, xq) - y0
% find the zero, intial guess must be good enough
y0 = fzero(yq, 1)

As noted in the comments, the intial guess must be "good enough" - this is not only for convergence within fzero but if, during the evaluation, a value of x is tested which is outside of your interpolation then it will break.

Example:

y0 = fzero(yq, 1)
% >> Exiting fzero: aborting search for an interval containing a sign change
%    because NaN or Inf function value encountered during search.
%    (Function value at 0.971716 is NaN.)

y0 = fzero(yq, 5)
% >> y0 = 3.5, as expected from the input data.
Wolfie
  • 27,562
  • 7
  • 28
  • 55
-1

Well, Since you want to use Linear Interpolation model in order to know interpolated value all you need is 2 samples around it.

For example, if you wonder when you get the value y = 3.5 all you need to find 2 adjacent points with one having value lower than 3.5 and the other value higher than 3.5.

Then all needed is to use Line Equation to infer the exact value of x at the point.

What I'm trying to say is if you only interested to find the x for a certain y value, there is no need to interpolate all data.

Royi
  • 4,640
  • 6
  • 46
  • 64