【问题标题】:Bisection root method in MATLAB [duplicate]MATLAB中的二等分法[重复]
【发布时间】:2015-09-20 02:23:17
【问题描述】:

我是 MATLAB 新手,我想知道为什么我的二分法代码无法运行,代码如下:

function [ r ] = bisection1( f1, a, b, N, eps_step, eps_abs )
    % Check that that neither end-point is a root
    % and if f(a) and f(b) have the same sign, throw an exception.

    if ( f1(a) == 0 )
    r = a;
    return;
    elseif ( f1(b) == 0 )
    r = b;
    return;
    elseif ( f1(a) * f1(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;

        % 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 ( f1(c) == 0 )
            r = c;
            return;
        elseif ( f1(c)*f1(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_step )
            if ( abs( f1(a) ) < abs( f1(b) ) && abs( f1(a) ) < eps_abs )
                r = a;
                return;
            elseif ( abs( f1(b) ) < eps_abs )
                r = b;
                return;
            end
        end
    end

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

我定义了

function y=f1(x)
    y=x^3+x-3;
end

在另一个脚本中,但是当我输入 bisection1(f1,1,2,100,10^-6,10^-6) 时它没有运行。

你能帮我完成这个任务吗?

【问题讨论】:

  • 您应该回到获得此代码的 MATLAB 书籍。 f1 现在也是一个函数,需要输入参数,这意味着您不能将它作为参数传递给 bisection1
  • Right :) 但后来我尝试了 bisection1(f1(x),1,2,100,10^-6,10^-6) 并没有奏效。

标签: matlab


【解决方案1】:

实际上,唯一错误的是您运行脚本的命令。因为您在文件中定义了f1,所以您无法将函数名称提供给您的bisection1 函数。您必须提供一个句柄。为此,只需键入:

bisection1(@f1,1,2,100,10^-6,10^-6)

注意“@”符号。如果您在命令提示符中定义f1,如下所示: f1 = @(x) x.^3+x-3;

然后你可以像上面那样简单地传递它。

在此处阅读有关@ 符号的更多信息:function handles

【讨论】:

  • 澄清一下,@ 在 MATLAB 中定义了一个 anonymous function
  • 其实没有。 @ 只是一个函数句柄。像我在回答中所做的那样,或者像在您显示的页面上那样使用它,会为匿名函数创建一个 handle ,但它也是命名函数的函数句柄。请注意,您链接的页面上的第一个示例显示“为匿名函数创建 句柄”。我已经更新了我的答案,在函数句柄上包含了一个链接。
  • 很好的解释,干杯!
  • 非常感谢 :),但为什么投反对票?
猜你喜欢
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
相关资源
最近更新 更多