Matlab - 用户定义的函数作为函数的参数

时间:2013-12-12 17:07:14

标签: matlab

所以我正在尝试编写一个函数,该函数将把secant方法实现到一个函数(f),该函数将由用户输入并将每次迭代的结果添加到向量中。我得到一个错误,声明x未定义,这是可以理解的,但我不确定如何定义它。我试图以一种方式来编写它,其中参数f可以是x的函数,例如。 x ^ 3 +12,而不是单独的函数文件的名称。

function [xans, xi, iter] = secant( f, x0, x1, tol )

    k = 1;
    a = x0;
    b = x1;
    c = f(b)*((b-a)/(f(b)-f(a)));

    while abs(c) >= tol
        xi(k) = b-c;
        a = b
        b = xi(k)
        k = k+1;

    end
disp(x)
disp(xi)
disp(iter)

3 个答案:

答案 0 :(得分:2)

你似乎对Matlab中的循环和函数有点困惑。您编写的函数不会对循环内的变量进行任何更新。当你写

c = f(b) * (b-a) / (f(b) - f(a));

c中存储一个值,但每次循环时它都不会自动更新c。相反,我会写这样的东西

function x1 = secant(f, x0, x1, tol)

y1 = f(x1);
y0 = f(x0);
while abs(y1) > tol
    tmp = x1;                              %// Store the old value of x1
    x1  = x1 - y1 * (x1 - x0) / (y1 - y0); %// Use the secant method to update x1
    x0  = tmp;                             %// x0 gets the old value of x1
    y0  = y1;                              %// We already know what f(x0) is
    y1  = f(x1);                           %// Need to re-compute f(x1)
end

然后您可以按如下方式调用。第一个参数称为函数句柄

>> secant( @(x)x^2-2, 0, 1, 1e-6)
ans = 
   1.414213562057320

答案 1 :(得分:0)

使用function_handle

[xans,xi,k] = secant(@myFunc,1,2,0.0001);

另外,在循环内调用函数,否则,它不会更新:

function [xans, xi, k] = secant(f, x0, x1, tol)

    %// etc.  

    while abs(c) >= tol
        c = f(b) * (b-a)/(f(b)-f(a));
        %// etc.
    end
end

答案 2 :(得分:0)

使用>>secant(@(x) x^3 +12, x0, x1, tol)

执行您的功能
相关问题