How to find the second interesection between two plots?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Meshooo
el 6 de En. de 2015
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 comentarios
Respuesta aceptada
Roger Stafford
el 6 de En. de 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 comentarios
dpb
el 6 de En. de 2015
Or, equivalent to the zero-crossing of the difference, use fsolve to find the zeros of the difference as the objective function.
Más respuestas (2)
dpb
el 10 de En. de 2015
Editada: dpb
el 10 de En. de 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 comentarios
Ver también
Categorías
Más información sobre Interpolation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!