What is wrong with my code for the bisection method!!?

조회 수: 3 (최근 30일)
Britney
Britney 2014년 10월 8일
댓글: Britney 2014년 10월 9일
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?

채택된 답변

Geoff Hayes
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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by