How to find the second interesection between two plots?
1 view (last 30 days)
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
0 Comments
Accepted Answer
Roger Stafford
on 6 Jan 2015
There is no reason to believe that the best-fitting straight lines to the two entire curves will intersect at the same points as the curves intersect. You can see that if you add your two straight lines to your plot.
Instead use a high order polynomial fit on the difference between A and B, and then use 'roots' to find the zero crossings. Or better still, plot the two curves and visually locate the approximate intersections. Then do a 'polyfit' for the difference in the immediate vicinity of each intersection and then use 'roots' for each of these.
2 Comments
dpb
on 6 Jan 2015
Or, equivalent to the zero-crossing of the difference, use fsolve to find the zeros of the difference as the objective function.
More Answers (2)
dpb
on 10 Jan 2015
Edited: dpb
on 10 Jan 2015
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.
0 Comments
See Also
Categories
Find more on Interpolation 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!