Bisection Method Piecewise function

6 次查看(过去 30 天)
So this is my code to try to bisect the piecewise function. But, when I run the code that was in the editor then I do
[r, iters] = bisectionF('f_feb15(x)', -2, .1)
matlab says
Undefined function or variable 'bisectionF'.
Sorry for such an elementary question. I am just beginning a scientific computing class and I am a math major so the only computer experience I have is LaTeX! Thank you so much for helping! I think it is something silly that I am missing. One of my friends said "I think it might have to do with your function file being saved with a different name then you actually called it." but I have no idea what this even means.
function[value]=f_feb15(x)
if x<=0
value=x^3+3*x+1
else if x>0
value=1+sin(x)
end %ends else if
end %ends else
clear all;
function[r, iters] = bisection(f, xL, xR)
for j=1:10
xM=(xL+xR)/2;
fM=feval(f, xM)
fL=feval(f, xL)
fR=feval(f, xR)
if fM*fL<0
xR=xM
else
xL=xM
end %end if
end %end for
if abs(fM)<10^(-5)
end %end if
end %function

回答(2 个)

Rahul Kalampattel
Rahul Kalampattel 2017-2-16
编辑:Rahul Kalampattel 2017-2-16
The function you have declared is called bisection, not bisectionF. When you want to call or use this function, you need to use the name you declared.
  2 个评论
Ewynne
Ewynne 2017-2-16
oh sorry, I had copy and pasted the wrong code. I have tried it with bisectionF in my code and it is still not working.
Rahul Kalampattel
Rahul Kalampattel 2017-2-16
Are you using the R2016b release of Matlab? If not, your function needs to be saved in a file called bisectionF.m (more info).
The file should also be in your current working directory.

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2017-2-17
Your bisectionF should be in bisectionF.m
Your f_feb15 should be in f_feb15.m
You should delete the "clear all" and you should never use it inside a function again. If you use "clear all" inside a script, it should be the very last thing in the script, and it should be a script dedicated to trying to get your MATLAB session unstuck. "clear all" is the "blow EVERYTHING up, especially yourself" command.
Your call
[r, iters] = bisectionF('f_feb15(x)', -2, .1)
should be
[r, iters] = bisectionF(@f_feb15, -2, .1)
or
[r, iters] = bisectionF('f_feb15', -2, .1) %not really recommended

类别

Help CenterFile Exchange 中查找有关 Historical Contests 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by