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 tells gives me the above error message. I've never passed a function name as an argument before. Where am I going wrong?
Matlab告诉我上面的错误信息。我之前从未传递过函数名作为参数。我哪里错了?
2 个解决方案
#1
35
You could also use function handles rather than strings, like so:
你也可以使用函数句柄而不是字符串,如下所示:
main.m
:
main.m文件:
...
func2(x, y, @func2eq); % The "@" operator creates a "function handle"
This simplifies func2.m
:
这简化了func2.m:
function t = func2(x, y, fcnHandle)
t = fcnHandle(x, y);
end
For more info, see the documentation on function handles
有关更多信息,请参阅有关函数句柄的文档
#2
9
You could try in func2.m
:
你可以试试func2.m:
function t = func2(x, y, funcName) % no quotes around funcName
func = str2func(funcName)
t = func(x, y)
end
#1
35
You could also use function handles rather than strings, like so:
你也可以使用函数句柄而不是字符串,如下所示:
main.m
:
main.m文件:
...
func2(x, y, @func2eq); % The "@" operator creates a "function handle"
This simplifies func2.m
:
这简化了func2.m:
function t = func2(x, y, fcnHandle)
t = fcnHandle(x, y);
end
For more info, see the documentation on function handles
有关更多信息,请参阅有关函数句柄的文档
#2
9
You could try in func2.m
:
你可以试试func2.m:
function t = func2(x, y, funcName) % no quotes around funcName
func = str2func(funcName)
t = func(x, y)
end