2010-04-28 166 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