I have a textbook that provides me with code and I'm using the code that they have in the textbook, verbatim, on my Mac and it refuses to work.
2 views (last 30 days)
function X = NewtonRoot(Fun, FunDer, Xest, Err, imax)
for i = 1:imax
Xi = Xest - Fun(Xest)/FunDer(Xest);
if abs((Xi - Xest)/Xest) < Err
X = Xi;
Xest = Xi;
if i == imax
fprintf('Solution was not obtained in %i iterations.\n',imax)
X = ('No answer');
and then to run the output for it, I use this command in the command window:
and it always returns 'Output argument "X" (and maybe others) not assigned during call to "NewtonRoot".'
I don't know what to do.
Roger Stafford on 9 Feb 2018
Edited: Roger Stafford on 9 Feb 2018
You have misinterpreted the fifth (last) argument to be entered into the function. You have set it to pi/2 which is so small that the code can only take one trip through the for-loop, which is almost certainly not enough times to converge to the correct root within your specified error of 0.0001. The meaning of ‘imax’ is the maximum number of times you want the code to iterate before giving up on the attempt. That is there to prevent going into an endless process that won’t quit, but it should be some number that is sufficiently large to allow you plenty of opportunity to converge to a root if one exists. Also it should be a positive integer if you want to be able to receive the error message which is in the function code.
Walter Roberson on 9 Feb 2018
Your code only assigns to X if the tolerance is met (desired case) or if your integer counter is exactly equal to the user provided imax. If the provided imax is less than 1 then after the for loop the variable will be set to empty. If you fail to meet the tolerance and the provided imax is not an integer then the error case will not be detected.
You can avoid these problems by using the structure
found = false
if tolerance is met
Return the appropriate number
return the error