查看单个帖子
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 在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告诉给我上面的错误信息。我以前从未传递过函数名称作为参数。我要去哪里错了?



回答:

您还可以使用函数句柄而不是字符串,如下所示:

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 有关更多信息,请参见函数句柄的文档。



更多&回答...
poster 当前离线   回复时引用此帖