Error while trying to code the Newton Method for a System of Equations

조회 수: 1 (최근 30일)
Roberto
Roberto 2012년 7월 13일
Hi there. This is my first post in the forum. My name is Roberto and I am from Spain. Since English is not my home language, please do not be too hard to me, thanks.
Well, I coded the Newton Method for a System of Equations. It looks like:
function [x,fx,iters]=sistemanewton_sept(func,jacobi,x0,TOL,maxit)
%x0 vector
mitol=2*TOL; iters=1;
x0=x0(:); %Lo ponemos como vector columna
while (mitol>TOL && iters<maxit)
J=jacobi(x0); f=func(x0); en=-J\f; %¿sale vector columna directamente?
x=x0+en; x0=x;
mitol=abs(func(x0));
iters=iters+1;
end
fx=func(x0);
if mitol>TOL
disp('ADVERTENCIA: No se pudo alcanzar la tolerancia deseada dentro del numero de iteraciones permitidas');
end
end
I don't know how to color the code. The error I get is:
??? Operands to the || and && operators must be convertible to logical scalar values.
Error in ==> sistemanewton_sept at 10
end
The functions I used in my code are: func and jacobi. They look like:
function f=func(x)
x1=x(1); x2=x(2);
f=[sqrt(x2*x2*x2/5), 0.25*(sin(x1)+cos(x2))]';
And:
function J=jacobi(x)
x1=x(1); x2=x(2);
J=[0, sqrt(0.45*x2); 0.25*cos(x1), -0.25*sin(x2)];
That error is driving me crazy, since I never got it before. As I could read in some other post, that error is related to the way I use the "&&" operator, which must be only used to compare scalars. I am already comparing Scalars so...
Thank you so much.
  댓글 수: 1
Star Strider
Star Strider 2012년 7월 13일
편집: Star Strider 2012년 7월 13일
Your code looks good to me, but I may be missing something. To start troubleshooting, I suggest you put before your ‘while’ loop something like:
TestTol = mitol>TOL
TestItr = iters<maxit
TestClass = class([TestTol TestItr])
The variables ‘TestTol’ and ‘TestItr’ should both evaluate as ‘logical’. If they do not, then you have to find and correct the problem. If they are both ‘logical’ and you continue to get the error, I suggest adding parentheses to your ‘while’ statement:
while (mitol>TOL) && (iters<maxit)
or:
while ((mitol>TOL) && (iters<maxit))
Since ‘func’ and ‘jacobi’ do not use the logical operators, they are probably not the problem.

댓글을 달려면 로그인하십시오.

답변 (1개)

Kye Taylor
Kye Taylor 2012년 7월 13일
The first time you enter the while loop, you are comparing scalars (assuming the input TOL is a scalar). However, when you overwrite mitol with the absolute value of the output from func, mitol becomes nonscalar since func outputs a 2-by-1 vector.
  댓글 수: 1
Roberto
Roberto 2012년 7월 13일
편집: Roberto 2012년 7월 13일
Oh... you are right, I forgot f(x0) was a vector... I replaced that line with this new one: mitol=norm(func(x0));
Thank you Kye Taylor, very helpful.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by