2012-10-05 54 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.穆斯特,我會標記它。