Error while trying to code the Newton Method for a System of Equations
1 次查看(过去 30 天)
显示 更早的评论
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
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!