Debugging Newton's Method code in two variables,

2 visualizaciones (últimos 30 días)
Noob
Noob el 21 de Sept. de 2020
Comentada: Ameer Hamza el 21 de Sept. de 2020
Hi,
I wrote a simple code for Newton's Method in two variables but am having some trouble debugging it. Here's the message I get:
Index exceeds matrix dimensions.
Error in Root_finding_practice>@(x)[cos(x(2)),-x(1)*sin(x(2));x(2)*cos(x(1)),sin(x(1))]
Error in Root_finding_practice (line 34)
x(i+1) = x(i) - ( inv( J( x(i) ) ) * f( x(i) ) );
The function file code is:
function F = nonlinear_equations(x)
F(1) = x(1) * cos( x(2) );
F(2) = x(2) * sin( x(1) );
end
and the script file code is:
f = @(x) nonlinear_equations;
% Jacobian
J = @(x) [ cos( x(2) ), -x(1)*sin(x(2));
x(2) * cos(x(1)), sin(x(1)) ];
x = [ 1, 1 ];
for i = 1:1000 % it should be stopped when tolerance is reached
x(i+1) = x(i) - ( inv( J( x(i) ) ) * f( x(i) ) );
if( abs( f( x(i+1) ) ) < 0.0001 ) % tolerance
disp(double(x(i+1)));
break;
end
end
What am I missing? I suspect it's the way I've defined the Jacobian anonymous function ...
Thanks,

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 21 de Sept. de 2020
Editada: Ameer Hamza el 21 de Sept. de 2020
Check this code
f = @(x) nonlinear_equations(x);
% Jacobian
J = @(x) [cos( x(2) ), -x(1)*sin(x(2));
x(2)*cos(x(1)), sin(x(1))];
x = [1; 1];
for i = 1:1000 % it should be stopped when tolerance is reached
x(:,i+1) = x(:,i) - inv(J(x(:,i)))*f(x(:,i));
if( abs(f(x(:, i+1))) < 0.0001) % tolerance
disp(double(x(:, i+1)));
break;
end
end
function F = nonlinear_equations(x)
F = zeros(2, 1);
F(1) = x(1) * cos( x(2) );
F(2) = x(2) * sin( x(1) );
end
  8 comentarios
Noob
Noob el 21 de Sept. de 2020
Oh, I see; I just have to define the inputs as a vector first.
Thanks again, Ameer!
Ameer Hamza
Ameer Hamza el 21 de Sept. de 2020
Yes, input need to be passed as vector.
I am glad to be of help :)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by