【问题标题】:Defining function in matlab which uses a function as a parameter在matlab中定义函数,它使用函数作为参数
【发布时间】:2012-01-21 18:47:44
【问题描述】:

我想定义一个这样的函数:

function f = f1(fun,a,b,c)
f = c*fun(a+b);

这里的fun 是我在使用函数f 时会传递的一些函数。 如何在 Matlab 中做到这一点?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    你试过了吗?学习 matlab 之类的工具最好的方法就是尝试一下!

    实际上,您甚至不需要创建 m 文件函数。我将在这里使用函数句柄来完成。

    fun = @(x) sin(x);
    f1 = @(f,a,b,c) c*f(a+b);
    f1(fun,2,3,4)
    
    ans =
          -3.8357
    

    我也可以将 f1 定义为 m 文件函数,但这需要我保存一个文件。何必呢?

    【讨论】:

      【解决方案2】:

      您正在寻找的是function handle

      您可以通过在函数名前面加上“at”符号('@')来获取函数的函数句柄(在以下情况下为sqrt):

      a = 1;
      b = 2;
      c = 3;
      fun = @sqrt;        % obtain the function handle of sqrt()
      f = f1(fun, a,b,c); % pass the function handle of sqrt() into your function f1().
      

      当您使用fun 时,就好像您在使用sqrt 函数。

      更多详情,您还可以参考另一个 Stackoverflow 问题:function handle in MATLAB

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 2011-02-13
        • 1970-01-01
        • 2019-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多