在 Matlab 中将函数作为参数传递 [英] Passing functions as arguments in Matlab

查看:64
本文介绍了在 Matlab 中将函数作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,它以两个数组和另一个函数的名称作为参数.

I'm trying to write a function that is gets two arrays and the name of another function as arguments.

例如

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:

function t = func2(x, y, fcnHandle)
    t = fcnHandle(x, y);
end

有关更多信息,请参阅有关函数句柄的文档

For more info, see the documentation on function handles

这篇关于在 Matlab 中将函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆