Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 718
haifisch123 Avatar asked Oct 20 '25 23:10

haifisch123


1 Answers

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])
like image 65
Luis Mendo Avatar answered Oct 23 '25 17:10

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!