How to find the second interesection between two plots?
Show older comments
Dear all,
I have two data sets, A and B (117 values each), and the values are included in the attached txt file, and their plot figure as follows:

As we can see from the plot, the two data sets intersect two times. My question is how to find the second intersection Xc?
I tired to use the polyfit but it seems not working because there are two intersections. I tried the following code:
x = 1:117;
hold on;
plot(x, A, 'g-', 'LineWidth', 2);
plot(x, B, 'r-', 'LineWidth', 2);
leftCoefficients = polyfit(x,A,1);
rightCoefficients = polyfit(x,B,1);
xc = (rightCoefficients (2) - leftCoefficients (2)) / (leftCoefficients(1) - rightCoefficients(1))
xc = 83.1228, but I think it should be some value close to 86.
Any idea how to find correct Xc value?
Any help will be appreciated.
Meshoo
Accepted Answer
More Answers (2)
Regarding your last version/query...
If you only care to the nearest index location, sure. The same idea can be written more succinctly as...
>> find(diff(A>B),1,'last')+1
ans =
86
>>
It'll find the rightmost intersection presuming that there is at least one; for multiple crossings it'll be the first from the RHS of the plot; if only one it'll be that one of course. The '+1' accounts for the fact that the length(diff(x)) is one less than length(x).
Change the 'k' value in the find call to get other crossing locations if such exist. Results of more than one come out sorted, the 'last' argument simply means if there were yet another crossing its index would be lower yet.
If need/want the actual intersection values, could use above as the crude locator then fit a small area of each curve around these points and solve for the intersection as previously indicated.
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!