allcrossings

Locate all intersections of a pair of functions f1 and f2, on a finite domain
6 Downloads
Updated 2 Mar 2023

View License

ALLCROSSINGS is a rootfinding tool , that is used to locate all points where a pair of functions cross in the plane. It solves for the locations x, where f1(x)==f2(x). As a simple example, here is the use of allcrossings, on the problem sin(x)==cos(x). We expect those solutions happen at the points (n+1/4)*pi. The search was done on the interval [-10,10].
xloc = allcrossings(@sin,@cos,[-10,10])
xloc =
-8.6394 -5.4978 -2.3562 0.7854 3.927 7.0686
If I now divide by pi, we should expect to see solutions that are all off from an integer by exactly 1/4.
xloc/pi
ans =
-2.75 -1.75 -0.75 0.25 1.25 2.25
The tool initially samples the supplied interval at equally spaced points, locating sub-intervals where a crossing must occur, then it uses fzero on that bracketed interval.
ALLCROSSINGS can also be used to identify crossings of a function with a constant. In this example, I used it to locate the points where y=2*x+tan(x) crosses the line y==1, on the interval [0,10].
xloc = allcrossings(@(x) 2*x + tan(x),1,[0,10])
xloc =
0.32919 1.5708 1.9113 4.7124 4.8274 7.854 7.9213
As one should expect though, the function here has singularities, where while it technically crosses the constant line y==1, they are not actually intersections. Those points are easily enough identified though, since wheere the function passes through a discontinuity, we see those points are clearly identified.
fun = @(x) 2*x + tan(x);
fun(xloc)
ans =
1 -1.2093e+15 1 3.5109e+14 1 2.5914e+14 1
I intentionally do not try to remove those locations, since they could technically be called a crossing point.

Cite As

John D'Errico (2026). allcrossings (https://www.mathworks.com/matlabcentral/fileexchange/125585-allcrossings), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2022b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Version Published Release Notes
1.0.0