1

I know there must be a really simple answer to this question, but I just can't seem to find it. (Guess I'm probably Googling the wrong terms.)

I am plotting some data in Matlab using the plot(x, data) function.

I want to find the x-intercept(s) of the line, i.e. the point(s) where y = 0.

In some cases, it may be that the data vector doesn't actually contain values equal to zero, so it's not just a matter of finding the indexes of the elements in data which are equal to zero, and then finding the corresponding elements in the x vector.

Like I said, it's a really simple problem and I'd think there's already some in-built function in Matlab...

Thank you for your help.

Rachel
  • 1,722
  • 8
  • 29
  • 34
  • In case there is no point with `y` exactly equal to 0, do you want a closest point to y==0 or you want to interpolate between closest points or may be through the whole line series? – yuk Apr 02 '12 at 20:37
  • @yuk The data I have always intersects the x-intercept. So even though the vector itself does not have 0 as one of its values, I'd like to get the point where the line (plotted by Matlab) intersects the x-axis. – Rachel Apr 02 '12 at 20:40

3 Answers3

3

If you want to find X-intercept as interpolate between 2 closest points around X axes you can use INTERP1 function:

x0 = interp1(y,x,0);

It will work if x and y are monotonically increasing/decreasing.

yuk
  • 19,098
  • 13
  • 68
  • 99
0

You can make a linear fit (1st order polynomial) to your data, then, from the slope and Y intercept of the fitted line, you'll be able to find X intercept. Here is an example:

x1 = 1:10;
y1 = x1 + randn(1,10);
P = polyfit(x1,y1,1);
xint = -P(2)/P(1);

if you want to know what is the slope and y_int, here it is:

Slope = P(1);  % if needed 
yint = P(2);   % if need
AlFagera
  • 91
  • 1
  • 10
0
x=-1.999:0.001:1.999;
y=(x-1).*(x+1); 
plot(x,y) 
hold on
plot(x,zeros(length(x),1),'--r') 
find(abs(y)<1e-3)

So the last part will guarantee that even there is not exact y-intercept, you will still get a close value. The result of this code are the indices that satisfy the condition.

jkt
  • 2,538
  • 3
  • 26
  • 28