New to MATLAB - trying to write bisection method?

10 次查看(过去 30 天)
Hello, I'm brand new to MATLAB and am trying to understand functions and scripts, and write the bisection method based on an algorithm from our textbook. However, I'm running into problems. Could anyone help me please?
Here is my code:
function [f] = Bisection(a,b,Nmax,TOL)
f = x^3 - x^2 + x;
i=1;
BisectA=f(a);
while i <= Nmax
p=a+(b-a)/2;
BisectP=f(p);
if BisectP == 0 || (b-a)/2 < TOL
disp('p');
end
i=i+1;
if BisectA*BisectP > 0
a=p;
BisectA=BisectP;
else
b=p;
end
end
disp('Method failed after num2str(Nmax) iterations, Nmax=', Nmax);
Thanks.
  3 个评论
youcef mokrane
youcef mokrane 2020-11-9
编辑:Walter Roberson 2020-11-9
x=4:4.7
f=tan(x)-x
a=4
b=4.7
fa=tan(a)-a
fb=tan(b)-b
n=1
n0=5000
while n<5000
p=(a+b)/2
fp=tan(p)-p
n=n+1
if fa*fp>0
a=p
else
b=p
end
end
Walter Roberson
Walter Roberson 2020-11-9
Why are you bothering to do x=4:4.7 ? The default increment for the colon operator is 1, so 4:4.7 is the same as 4:1:4.7 which is just going to be 4 .
Why are you assigning to n0 when you do not use it?

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2013-12-15
编辑:Walter Roberson 2013-12-16
Your line
f = x^3 - x^2 + x;
does not define a function. Try
f = @(x) x^3 - x^2 + x;
  10 个评论
A_J Khan
A_J Khan 2017-9-18
编辑:Walter Roberson 2017-9-18
function p = bisection(f,a,b)
|
Error: Function definitions are not permitted in this
context.
I have this error with above code....???
Walter Roberson
Walter Roberson 2017-9-18
You can never define a function at the command prompt: you have to store a function inside a .m file; in this case, bisection.m
In versions up to R2016a you cannot store a function inside a script file (a .m file that does not start with the word "function" or "classdef"). That changed in R2016b.

请先登录,再进行评论。

更多回答(1 个)

Frank Cano
Frank Cano 2019-4-15
Here are some Bisection method examples

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by