This solution is an improvement on Amro's answer . Instead of using fzero you can simply calculate the intersection of the line by looking for the transition in the first difference of the series created by a logical comparison with LineValue . So, using Amro data:
>> x = linspace (-100,100,100);
>> y = 1-2. * exp (-0.5 * x. ^ 2. / 20) ./ (2 * pi) + randn (size (x)) * 0.002;
>> LineValue = 0.8;
Find the starting indices of those consecutive point segments that exceed LineValue :
>> idx = find (diff (y> = LineValue))
idx =
48 52
Then you can calculate the x position of the intersection points using weighted averages (e.g. linear interpolation):
>> x2 = x (idx) + (LineValue - y (idx)). * (x (idx + 1) - x (idx)) ./ (y (idx + 1) - y (idx))
x2 =
-4.24568579887939 4.28720287203057
Schedule them to check the results:
>> figure;
>> plot (x, y, 'b.-', x2, LineValue, 'go', [x (1) x (end)], LineValue * [1 1], 'k:');

The advantages of this approach are as follows:
- The definition of intersection points is vectorized, so it will work regardless of the number of intersection points.
- Defining intersection points is arithmetically supposedly faster than using
fzero .
source share