在Matlab中将函数作为参数传递

27
我正在尝试编写一个函数,它接受两个数组和另一个函数的名称作为参数。
例如:
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告诉我上述错误信息。我以前从未将函数名作为参数传递过。我做错了什么?

2个回答

41
你可以使用函数句柄而不是字符串,像这样:

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

更多信息请参阅函数句柄的文档。


10
你可以尝试在func2.m中:
function t = func2(x, y, funcName)  % no quotes around funcName
    func = str2func(funcName)
    t = func(x, y)
end

至少在 v.2015 中,如果您不引用 funcName,则 MATLAB 解释器会期望提供参数。您是否认为 funcName 是一个句柄? - Carl Witthoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接