What is wrong with my code for the bisection method!!?
3 次查看(过去 30 天)
显示 更早的评论
So I have this code I need too use on my a function.
I have made m. function file with the function I want to calculate.
f=@(x)(x-2.5).*exp(-0.5*(x-2).^2)+0.2;
x=my_bisect(f,[-1,0],1e-5);
m =(a+b)/2;
disp(m);
And in another file I have this code:
function m=my_bisect(funktion, int , tol )
a = int (-1);
b = int (0);
fa =funktion(a) ;
fb =funktion(b) ;
disp(fa)
disp(fb)
msg=sprintf('??? error.');
while b-a > tol
m = (a+b)/2;
fm = funktion(m);
if fm==0
disp(msg)
return
end
if fa * fm < 0
b = m;
fb = fm;
else
a = m;
fa = fm;
end
end
When I try running function file to find m Matlab returns: Attempted to access int(-1); index must be a positive integer or logical.
What is wrong?
0 个评论
采纳的回答
Geoff Hayes
2014-10-8
Britney - the error message is telling you that you are trying to access an array named int with an index that is not positive or a logical (true/1). In your case, the first two lines of your code are
a = int (-1);
b = int (0);
and you are using -1 and 0 to index the array. As neither are positive, the error message makes sense. If a and b are the endpoints for your interval, then you can initialize them as
a = int(1);
b = int(2);
Though you may want to rename this input variable as interval as int could be mistaken for integer.
Note that since you are using double precision, the line
if fm==0
is not guaranteed to ever evaluate to true. This is fine for integers, but for variables of type double, you would typically do something like
if abs(fm)<tol
where tol is some small number (could be eps).
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!