functionmatlabnestedfunction-reference

Nested functions don't recognize input


Here's a minimal example of my problem:

innerFunc([2, 4, 5]) % works fine
outerFunc(innerFunc, [2, 4, 5]) % doesn't work

function out = innerFunc(my_vec) 
    my_vec % not recogniced when called from outerFunc
    out = -1;
end

function out = outerFunc(func, my_vec) 
    out = func(my_vec);
end

This is the output of the code:


my_vec =

     2     4     5


ans =

    -1

Not enough input arguments.

Error in nested_funcs_bug>innerFunc (line 5)
    my_vec % not recogniced when called from outerFunc

Error in nested_funcs_bug (line 2)
outerFunc(innerFunc, [2, 4, 5]) % doesn't work

>> 

I don't know why the eror in line 2?

Especially since "innerFunc" usually works and I pass it an input in the outerFunc function.


Solution

  • It seems that in

    outerFunc(innerFunc, [2, 4, 5]) % doesn't work

    you intend to pass innerFunc as an input to outerFunc. However, what that line does is call innerFunc (which gives an error because the input to that function is missing); and the output of that function call would then be used as input to outerFunc.

    To pass (a handle of) innerFunc as an input to outerFunc you need to prepend @ (more information here):

    outerFunc(@innerFunc, [2, 4, 5])