how to solve newton method ?
7 ビュー (過去 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!
