# 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)
Elias Beaini on 9 Feb 2018
Answered: Walter Roberson on 9 Feb 2018
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;
break
end
Xest = Xi;
end
if i == imax
fprintf('Solution was not obtained in %i iterations.\n',imax)
end
and then to run the output for it, I use this command in the command window:
>> xSolution=NewtonRoot(@Fun1,@FunDer1,0.54,0.0001,pi/2)
and it always returns 'Output argument "X" (and maybe others) not assigned during call to "NewtonRoot".'
I don't know what to do.
##### 2 CommentsShowHide 1 older comment
Stephen23 on 9 Feb 2018
Edited: Stephen23 on 9 Feb 2018
"but I don't know if this is true or why it isn't working in general"
It is working. It is doing exactly what you told it to do:
NewtonRoot(@Fun1,@FunDer1,0.54,0.0001,pi/2)
calls it with imax of pi/2, and when you look at the code you can see where imax is used:
for i = 1:imax
Of course 1:pi/2 produces the sequence 1, so this for loop will iterate exactly once, just like you asked it to.

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
for....
...
if tolerance is met
found =true
break
end
end
if found
Return the appropriate number
else
return the error
end

### Categories

Find more on Entering Commands in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by