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.

조회 수: 1 (최근 30일)
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)
X = ('No answer');
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
Elias Beaini
Elias Beaini 2018년 2월 9일
Other people are using this same code and it works for them (I'm guessing because they are on PC), but I don't know if this is true or why it isn't working in general
Stephen23
Stephen23 2018년 2월 9일
편집: Stephen23 2018년 2월 9일
"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.

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

답변 (2개)

Roger Stafford
Roger Stafford 2018년 2월 9일
편집: Roger Stafford 2018년 2월 9일
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
Walter Roberson 2018년 2월 9일
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

카테고리

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