how to solve newton method ?
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
Jan
2018-11-6
编辑:Jan
2018-11-6
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
2018-11-7
Another typo in your code:
iter = itr+1;
It looks like this should be
iter = iter+1;
回答(1 个)
Jan
2018-11-6
编辑:Jan
2018-11-7
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 个评论
Rik
2018-11-7
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)]);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
