Show intersection of two curves

If I have two graphs defined by two different equations:

x = 0:0.01:30; y1 = x .^2 + 2; y2 = x .^3 ; 

and I draw them like

 plot(x, y1, x, y2); 

How to get a small ring around the intersection point programmatically (as in the following figure)?

enter image description here

+7
source share
4 answers

You will need to find the intersection point (p x , p y ) manually:

 idx = find(y1 - y2 < eps, 1); %// Index of coordinate in array px = x(idx); py = y1(idx); 

Remember that we are comparing two numbers in a floating point representation, so instead of y1 == y2 we have to set the tolerance. I chose it as eps , but it's up to you.

To draw a circle around this point, you can calculate its points and then draw them, but the best approach would be to build one point with a bloated circle marker ( Jonas credit for this sentence):

 plot(px, py, 'ro', 'MarkerSize', 18) 

Thus, the size of the circle does not depend on the axes and aspect ratio of the graph.

Example

 x = 0:0.01:30; y1 = x .^ 2 + 2; y2 = x .^ 3; %// Find point of intersection idx = find(y1 - y2 < eps, 1); px = x(idx); py = y1(idx); figure plot(x, y1, x, y2, px, py, 'ro', 'MarkerSize', 18) axis([0 10 0 10]) 

This should result in the following plot: result

+11
source

In your example, when you have x, y1 and y2 what you can do is

 idx = find(abs(y1 - y2) == min(abs(y1 - y2))); xInter = x(idx) yInter = y1(idx) % or y2(idx) 

If you have x1, y1 and x2, y2, where x1 ~ = x2 you can first perform 1D interpolation using

 yy2 = interp1(x2, y2, x1); 

then apply

 idx = find(abs(y1 - yy2) == min(abs(y1 - yy2))); xInter = x1(idx) yInter = y1(idx) % or yy2(idx) 
+2
source

This is a great entry from @EitanT, however, I would like to supplement this with another (automatic) way to find the intersection (assuming there is one, and the graphs behave beautifully).

Here is our starting point:

 x = 0:0.01:30; y1 = x .^2 + 2; y2 = x .^3 ; 

First of all, we check whether these values ​​are exactly equal, for non-discrete situations without a floating point, this should be enough:

 idx = find(y1==y2) 

If they are never recorded to be exactly the same, the intersection occurs if one is superior to the other, so we look at the difference:

 if isempty(idx) d = y1-y2; % At the moment of crossing, the sign will change: s = diff(sign(d)); % Now just find the point where it changes f = find(s,1); end 

To summarize this in a compact form without additional variables, I would recommend using:

 idx = find(y1==y2) if isempty(idx) idx = find(diff(sign(y1-y2)),1) end 
+1
source

Especially knowing the functions, you can use the symbolic mathematical toolbar.

 y1 = x .^2 + 2; y2 = x .^3 ; syms x real intersection=simplify(solve(y1==y2)) 

Use vpa(intersection) to convert it to a number or double(intersection) to convert it to a floating point value.

+1
source

All Articles