how to solve newton method ?
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Jan
le 6 Nov 2018
Modifié(e) : Jan
le 6 Nov 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
le 7 Nov 2018
Another typo in your code:
iter = itr+1;
It looks like this should be
iter = iter+1;
Réponses (1)
Jan
le 6 Nov 2018
Modifié(e) : Jan
le 7 Nov 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 commentaires
Rik
le 7 Nov 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)]);
Voir également
Catégories
En savoir plus sur Function Creation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
