how to solve newton method ?
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
hello,
what is wrong with my code .. I get Error in fevel .
fun =inline( '[x(1)^2+ x(2)^2 + x(3)^2 -1 ;
x(1)^2 + x(3)^2-0.25 ;
x(1)^2+ x(2)^2 + 4*x(3) ]');
J = inline ('[2*x(1), 2*x(2), 2*x(3);
2*x(1), 0, 2*x(3);
2*x(1), 2*x(2), -4]');
x0 = [1;1;1]; tol= 0.00001; maxit= 10;
xold = x0; iter=1;
while (iter<= maxit)
y= -feval(J,xold)\ feval(fun,xold);
xnew=xold+y';
dif = norm(xnew-xold);
dis([iter xnew dif ]);
if dif <= tol
x=xnew ;
disp (' Newton method has converged '), return;
else
xold= xnew;
end
iter = itr+1;
end
disp('Newton method did not converge')
x = xnew ;
2 comentarios
Jan
el 6 de Nov. de 2018
Editada: Jan
el 6 de Nov. de 2018
Using anonymous functions is smarter than the old inline method.
If you get an error message, please be so kind and post a copy of it. It is useful to know, what the error is.
The code fails after a copy&paste already, because the char array inside the inline call is continued over the line breaks.
Rik
el 7 de Nov. de 2018
Another typo in your code:
iter = itr+1;
It looks like this should be
iter = iter+1;
Respuestas (1)
Jan
el 6 de Nov. de 2018
Editada: Jan
el 7 de Nov. de 2018
One problem is hidden inside:
fun =inline( '[x(1)^2+ x(2)^2 + x(3)^2 -1 ;
x(1)^2 + x(3)^2-0.25 ;
x(1)^2+ x(2)^2 + 4*x(3) ]');
You can omit commas in vectors and unfortunately Matlab interprets [a -1] as 1x2 vector, while [a - 1] is a scalar. So insert spaces around all operators to be clear and unique:
% [EDITED] leading quotes added...
fun = inline('[x(1) ^ 2 + x(2) ^ 2 + x(3) ^ 2 - 1;', ...
'x(1) ^ 2 + x(3) ^ 2 - 0.25;', ...
'x(1) ^ 2 + x(2) ^ 2 + 4 * x(3)]');
Note that the editor marks inline as ancient method. Prefer to use an anonymous function instead.
The next problem occurs in
dis([iter xnew dif ]);
Do you mean "disp"? The concatenation does not work, because iter is a scalar, but xnew is a column vector.
disp(iter)
disp(xnew)
disp(dif)
2 comentarios
Rik
el 7 de Nov. de 2018
As mentioned previously, you should use anonymous functions instead.
Also, if you post something here, post it as text, so we don't have to type everything, but can correct your code here. In this case, Jan made a small typo that is easily correctable:
fun = inline(['[x(1) ^ 2 + x(2) ^ 2 + x(3) ^ 2 - 1;', ...
'x(1) ^ 2 + x(3) ^ 2 - 0.25;', ...
'x(1) ^ 2 + x(2) ^ 2 + 4 * x(3)]']);
Moving to an anonymous function is easy from here:
fun = @(x) [x(1) ^ 2 + x(2) ^ 2 + x(3) ^ 2 - 1; ...
x(1) ^ 2 + x(3) ^ 2 - 0.25; ...
x(1) ^ 2 + x(2) ^ 2 + 4 * x(3)]);
Ver también
Categorías
Más información sobre Function Creation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
