MATLAB: How to find points of intersection between a curve and horizontal line

curvehorizontalintersectionlineOptimization Toolbox

I have a curve, not defined via a function handle, but evaluated at a number of points. I would like to find all the points of intersection of this curve with a horizontal line.

Best Answer

In general, the intersection points of a horizontal line and a curve can be found by looking for the changes in sign in the difference of the horizontal line and curve. For example,
X = (0:0.01:10)';
Y = sin(X); % curve
H = 0.5 + 0*X; % horizontal line
To determine the points of intersection, examine neighbouring x-values that flip the sign of the difference vector.
sign_flip = (Y(2:end)-H(2:end)).*(Y(1:end-1)-H(1:end-1)); % when the curve crosses the line the difference vector will flip sign and the product of neighbouring points will be negative
X(sign_flip < 0) % gives approximate x-values for where the curve and line crossed
The 'X' values reported will be an approximation to the points of intersection. This approximation can be improved by increasing the sampling rate.
Related Question