2012-10-05 44 views
0

可能重复:
Passing a function as argument to another function传递函数作为参数在MATLAB函数

下面是二分法一个简单的代码。我想知道如何能够通过我选择的任何函数作为参数而不是硬编码函数。

% This is an implementation of the bisection method 
% for a solution to f(x) = 0 over an interval [a,b] where f(a) and f(b) 
% Input: endpoints (a,b),Tolerance(TOL), Max # of iterations (No). 
% Output: Value p or error message. 

function bjsect(a,b,TOL,No) 
% Step 0 
if f(a)*f(b)>0 
    disp('Function fails condition of f(a),f(b) w/opposite sign'\n); 
    return 
end 
% Step 1 
i = 1; 
FA = f(a); 
% Step 2 
while i <= No 
    % Step 3 
    p = a +(b - a)/2; 
    FP = f(p); 
    % Step 4 
    if FP == 0 || (b - a)/2 < TOL 
     disp(p); 
    return 
    end 
    % Step 5 
    i = i + 1; 
    % Step 6 
    if FA*FP > 0 
     a = p; 
    else 
     b = p; 
    end 
    % Step 7 
    if i > No 
     disp('Method failed after No iterations\n'); 
     return 
    end 
end 
end 

% Hard coded test function 
function y = f(x) 
y = x - 2*sin(x); 
end 

我知道这是一个重要的概念,所以任何帮助,非常感谢。

+0

@ H.Muster是的,你是对的。我会标记它。干杯。 –

回答

1

最简单的方法是使用anonymous functions。在你的榜样,你会使用定义匿名函数外bjsect

MyAnonFunc = @(x) (x - 2 * sin(x)); 

您现在可以通过MyAnonFuncbjsect作为参数。它具有函数句柄的对象类型,可以使用isa进行验证。在bjsect内部,只需使用MyAnonFunc就好像它是一个函数,即:MyAnonFunc(SomeInputValue)

注意,当然你也可以包你写在一个匿名函数的任何功能,即:

MyAnonFunc2 = @(x) (SomeOtherCustomFunction(x, OtherInputArgs)); 

是完全有效的。

编辑:哎呀,刚才意识到这几乎肯定是另一个问题的重复 - 谢谢H.穆斯特,我会标记它。