Why do I get errors in my bisection algorithm and how can I improve my code?

Hi! I'm trying to make this bisection algorithm and can't get it to work. Depending on what I type in I get different kinds of errors. Why do I get the following errors and how can I improve my code into working?
>> x=bisect1(@y.^2,[0,2],1e-7)
Undefined function 'power' for input arguments of type 'function_handle'.
>> x=bisect1(@y*2-5,[0,2],1e-7)
Undefined function 'mtimes' for input arguments of type 'function_handle'.
>> x=bisect1(@y-5,[0,2],1e-7)
Undefined function 'minus' for input arguments of type 'function_handle'.
function x=bisect(f, int , tol )
funktion =@(x) f;
a = int (1); % left end - point
b = int (2); % right end - point
fa =funktion(a) ; % value at left end - point
fb =funktion(b) ; % value at right end - point
disp(fa)
disp(fb)
while b-a > tol % continue as long as the interval is longer
% than the given tolerance
x = (a+b)/2; % compute midpoint on current interval
fx = funktion(x); % compute f(x) at midpoint
if fx==0
return % break and return x
end
if fa * fx < 0 % solution is in left half of interval
b = x; % move right end - point
fb = fx; % move value at right end - point
else % solution is in right half or interval
a = x; % move left end - point
fa = fx; % move value at left end - point
end
end
x = (a+b)/2; % compute midpoint on last interval
disp(x);

 채택된 답변

the cyclist
the cyclist 2013년 9월 10일
편집: the cyclist 2013년 9월 10일
Call your function like this:
f = @(y) y.^2;
x=bisect(f,[0,2],1e-7)
and define your bisect.m function file like this:
function x=bisect(funktion, int , tol )
a = int (1); % left end - point
b = int (2); % right end - point
fa =funktion(a) ; % value at left end - point
fb =funktion(b) ; % value at right end - point
disp(fa)
disp(fb)
while b-a > tol % continue as long as the interval is longer
% than the given tolerance
x = (a+b)/2; % compute midpoint on current interval
fx = funktion(x); % compute f(x) at midpoint
if fx==0
return % break and return x
end
if fa * fx < 0 % solution is in left half of interval
b = x; % move right end - point
fb = fx; % move value at right end - point
else % solution is in right half or interval
a = x; % move left end - point
fa = fx; % move value at left end - point
end
end
x = (a+b)/2; % compute midpoint on last interval
disp(x);

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

질문:

2013년 9월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by