My Newton Raphson Script Stucks at first step

clc
a = input('Enter initial guess: ');
e = input('Tolerable error: ');
N = input('Enter maximum number of steps: ');
step = 1;
g = diff(f(x));
while abs(f(a))> e
if g(a) == 0
disp('Division by zero.');
break;
end
b = a - f(a)/g(a);
fprintf('step=%d\ta=%f\tf(a)=%f\n',step,a,f(a));
a = b;
if step>N
disp('Not convergent');
break;
end
step = step + 1;
end
fprintf('Root is %f\n', a);
I have function file called f.m . It consists:
function f= f(x)
f=cos(x)-x.*exp(x);
end
When I run it it stucks at first. It doesn't do other iterations. How can I figure it out? I need to have separate function file and call it like this.

Respuestas (1)

Torsten
Torsten el 28 de Mzo. de 2022
Editada: Torsten el 28 de Mzo. de 2022
a = 1.0;
e = 1e-6;
N = 30;
syms x
fsym = cos(x)-x*exp(x);
f = matlabFunction(fsym);
g = matlabFunction(diff(fsym,x));
step = 1;
%g = diff(f(x));
while abs(f(a))> e
if g(a) == 0
disp('Division by zero.');
break;
end
b = a - f(a)/g(a);
fprintf('step=%d\ta=%f\tf(a)=%f\n',step,a,f(a));
a = b;
if step>N
disp('Not convergent');
break;
end
step = step + 1;
end
fprintf('Root is %f\n', a);

2 comentarios

st0s
st0s el 28 de Mzo. de 2022
Thanks for answer but can you do it like I did? cos(x)-x*exp(x) this expression musn't be on script. I need call it from my f.m file. Also I need take input from user. I tried to fix it but got error when I did g = matlabFunction (diff(f(x));
Torsten
Torsten el 28 de Mzo. de 2022
Editada: Torsten el 28 de Mzo. de 2022
Then you must define f(x) twice:
syms x
fsym = cos(x)-x*exp(x);
g = matlabFunction(diff(fsym,x));
...
function value = f(x)
value = cos(x)-x*exp(x);
end
Or you define f as a function handle and not as a function:
f = @(x) cos(x)-x*exp(x);
g = eval(['@(x)' char(diff(f(x)))])
%or vectorized:
g = eval(['@(x)' vectorize(char(diff(f(x))))])
Or you calculate g = f'(x) using paper and pencil (my suggestion).

Iniciar sesión para comentar.

Categorías

Más información sobre Programming en Centro de ayuda y File Exchange.

Preguntada:

el 28 de Mzo. de 2022

Editada:

el 28 de Mzo. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by