Intersection of a linear and a non linear equation with Newton Raphson method

3 次查看(过去 30 天)
Hey guys,
I have this function. I would like to find the intersection between two functions. So when I plot the functions I can see my non linear function and the intersection point, but instead of plotting the linear function I have just a constant.
I hope you can help finding the root cause of my problem.
Thank you so much in advance!
This is the function that I use:
function [root] = function_newton_raphson(func, diff, x0, maxIteration, xMin, xMax, a, b)
x = x0;
root = 0;
Epsilon = 1e-6;
linear = a*x+b;
for i = 1:maxIteration
if diff(x(i)) < Epsilon
fprintf('Pitfall has occured. Try another initial guess\n')
return;
end
x(i+1) = x(i) - (func(x(i))-a*x(i)-b)/(diff(x(i))-a);
abs_error(i+1) = abs((x(i+1)-x(i))/x(i+1))*100;
if abs(x(i+1)-x(i)) < Epsilon
fprintf('The root has converged at x = %.10f\n', x(i+1));
root = x(i+1);
fplot(func, [xMin xMax])
hold on;
title('$ $ Newton-Raphson method to find intersection of f(x)', 'Interpreter', 'latex');
fplot(linear, [xMin xMax])
plot(root, linear, '*');
text(root, linear, '\leftarrow intersection WP');
legend(func2str(func));
grid on;
break;
else
fprintf('Iteration no: %d, current guess x = %.10f, error = %.5f\n', i, x(i+1), abs_error(i+1));
end
end
end
And I call it like this in the editor
func = @(x) 2*x.^2;
diff = @(x) 4*x;
x = function_newton_raphson(func, diff, 1.6, 50, 0, 5, 2, 1)
y = func(x)

采纳的回答

Alan Stevens
Alan Stevens 2020-11-6
Change
linear = a*x+b;
to
linear = @(x) a*x+b;
and
plot(root, linear, '*');
text(root, linear, '\leftarrow intersection WP');
to
plot(root, linear(root), '*');
text(root, linear(root), '\leftarrow intersection WP');

更多回答(0 个)

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by