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

5 ビュー (過去 30 日間)
Adam
Adam 2013 年 9 月 10 日
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 件)

カテゴリ

Help Center および File ExchangeDebugging and Analysis についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by