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
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 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Stephen23
am 9 Feb. 2018
Bearbeitet: Stephen23
am 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.
Antworten (2)
Roger Stafford
am 9 Feb. 2018
Bearbeitet: Roger Stafford
am 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.
0 Kommentare
Walter Roberson
am 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Transmitters and Receivers finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!