how to solve newton method ?
조회 수: 15 (최근 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!
