Rachel
Rachel

Reputation: 1772

How to find the x-intercept of a plot in Matlab

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.

Upvotes: 1

Views: 39205

Answers (3)

AlFagera
AlFagera

Reputation: 91

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

Upvotes: 0

yuk
yuk

Reputation: 19880

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.

Upvotes: 3

jkt
jkt

Reputation: 2578

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.

Upvotes: 0

Related Questions