2010-04-28 169 views
23

我想寫一個函數獲取兩個數組和另一個函數的名稱作爲參數。在Matlab中傳遞函數參數

例如

main.m: 

    x=[0 0.2 0.4 0.6 0.8 1.0]; 
    y=[0 0.2 0.4 0.6 0.8 1.0]; 

    func2(x,y,'func2eq') 

func 2.m : 
    function t =func2(x, y, z, 'func') //"unexpected matlab expression" error message here  
    t= func(x,y,z); 

func2eq.m: 
    function z= func2eq(x,y) 

    z= x + sin(pi * x)* exp(y); 

Matlab告訴我給了上述錯誤信息。我從來沒有傳過函數名稱作爲參數。我哪裏錯了?

回答

35

你也可以使用函數處理,而不是字符串,像這樣:

main.m

... 
func2(x, y, @func2eq); % The "@" operator creates a "function handle" 

這簡化func2.m

function t = func2(x, y, fcnHandle) 
    t = fcnHandle(x, y); 
end 

欲瞭解更多信息,請參閱function handles

9

你可以嘗試在func2.m

function t = func2(x, y, funcName) % no quotes around funcName 
    func = str2func(funcName) 
    t = func(x, y) 
end