I am having problems determining this basic logic. Given 2 functions: y1 and y2, plotted on x in MATLAB. How do you determine the intersections using simple for loop and if else statement. These y1 and y2 has more than one intersections. I am pretty sure that I am missing something in the loop
clc
clear
x = linspace(0,2);
y1 = 2.*x + 1;
y2 = exp(x);
tol = 0.05;
x_intercept = zeros(size(x));
y_intersect = zeros(size(x));
for i = 1:100
if abs(y1(i) - y2(i)) == tol
y_intersect = y2(x(i));
x_intercept = x(i);
end
end
plot(x,y1)
hold on
plot(x,y2)
plot(x_intercept, y_intersect,'xr');
When I researched this problem, all I found is using polyval/polyfit and the likes but those only show 1 intersection.
Try changing your for loop to:
ctr=1;
for i = 1:100
if abs(y1(i) - y2(i)) <= tol
y_intersect(ctr) = y2(i);
x_intercept(ctr) = x(i);
ctr=ctr+1;
end
end