在Matlab中传递函数作为参数 [英] Passing functions as arguments in Matlab
本文介绍了在Matlab中传递函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图编写一个函数,它获取两个数组和另一个函数的名称作为参数。
I'm trying to write a function that is gets two arrays and the name of another function as arguments.
例如。
e.g.
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告诉我上面的错误信息。我从来没有传过函数名称作为参数。
Matlab tells gives me the above error message. I've never passed a function name as an argument before. Where am I going wrong?
推荐答案
您也可以使用函数句柄而不是字符串,如下所示:
You could also use function handles rather than strings, like so:
main.m
:
...
func2(x, y, @func2eq); % The "@" operator creates a "function handle"
这简化了 func2 .m
:
This simplifies func2.m
:
function t = func2(x, y, fcnHandle)
t = fcnHandle(x, y);
end
有关更多信息,请参阅函数句柄
For more info, see the documentation on function handles
这篇关于在Matlab中传递函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文