Search code examples
matlabfunctionargumentshandlefunction-handle

Passing function name as argument in MATLAB


I know this question is already asked and answered here But I cannot make it work.

I have a simple function f1 :

function out = f1(x)
out = x^2 + 5;
end

and I want to have a "delegate" function that takes the function name as input. Below you can see my 2 trials :

% function out = delegate_function(the_input , func_handle)
% out = func2(the_input, func_handle);
% end

function out = delegate_function(the_input , funcname)
thefunc = str2func(funcname);
out = thefunc(the_input);
end

Both of them give the same error when I call this in the command window :

delegate_function(2 , f1); % I want ans = 9

Error using f1 (line 2)
Not enough input arguments.

What am I doing wrong?

Thanks for any help !


Solution

  • To make the version above working, you have to pass the name of the function, which is

    delegate_function(2 , `f1`);
    

    I would strongly recommend to use a function handle instead:

    function out = delegate_function(the_input , func_handle)
    out = func_handle(the_input);
    end
    

    Then you have to call delegate_function using:

    delegate_function(2 , @f1);