二分Matlab实现问题

时间:2014-04-27 13:02:06

标签: matlab bisection

你好我们必须实现二分法来找到区间[a,b]中函数的根。该算法应返回1.根" c" 2.功能值" yc" 3.迭代次数" itcount"。

这是我现在所拥有的:

   function [ r, c, yc, itcount] = bisection( f, a, b, N, eps )
% Check that that neither end-point is a root
% and if f(a) and f(b) have the same sign, throw an exception.

if ( f(a) == 0 )
r = a;
return;
elseif ( f(b) == 0 )
r = b;
return;
elseif ( f(a) * f(b) > 0 )
    error( 'f(a) and f(b) do not have opposite signs' );
end

% We will iterate N times and if a root was not
% found after N iterations, an exception will be thrown.

for k = 1:N
    % Find the mid-point
    c = (a + b)/2;
    yc = feval(f,c);
    itcount = abs(b-a)/2;
    % Check if we found a root or whether or not
    % we should continue with:
    %          [a, c] if f(a) and f(c) have opposite signs, or
    %          [c, b] if f(c) and f(b) have opposite signs.

    if ( f(c) == 0 )
        r = c;
        return;
    elseif ( f(c)*f(a) < 0 )
        b = c;
    else
        a = c;
    end

    % If |b - a| < eps_step, check whether or not
    %       |f(a)| < |f(b)| and |f(a)| < eps_abs and return 'a', or
    %       |f(b)| < eps_abs and return 'b'.

    if ( b - a < eps )
        if ( abs( f(a) ) < abs( f(b) ) && abs( f(a) ) < eps )
            r = a;
            return;
        elseif ( abs( f(b) ) < eps )
            r = b;
            return;
        end
    end
 end

 error( 'the method did not converge' );
end

我已经为我想找到根的函数创建了一个.m文件。并且该算法有效,但它只返回根,但不返回函数值和迭代次数。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的算法似乎是正确的。您应该将输出作为向量。

[r, c, yc, itcount] = bisection(@f,.......) 
像这样调用只会让你获得第一个元素

an = bisection(@f,.......)

看到这个主题 - &gt; MATLAB - multiple return values from a function?