Passing functions as arguments in Matlab

前端 未结 2 899
Happy的楠姐
Happy的楠姐 2020-11-30 04:35

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];
         


        
相关标签:
2条回答
  • 2020-11-30 05:25

    You could try in func2.m:

    function t = func2(x, y, funcName)  % no quotes around funcName
        func = str2func(funcName)
        t = func(x, y)
    end
    
    0 讨论(0)
  • 2020-11-30 05:37

    You could also use function handles rather than strings, like so:

    main.m:

    ...
    func2(x, y, @func2eq); % The "@" operator creates a "function handle"
    

    This simplifies func2.m:

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

    For more info, see the documentation on function handles

    0 讨论(0)
提交回复
热议问题