Passing a constant function handle to another function

I want to pass a constant function handle "simulate" to a function "fftest", so that the corresponding function in the function handle simulate is called during evaluation "fftest" with the provided arguments:
simulate = @depsim;
g = @(x,y) fftest(x,y,@simulate);
g(1,1);
% in separate files:
function ret = depsim(a,b)
ret = ones(a,b);
end
function fftest(a,b,simulate)
disp(simulate(a,b));
disp("it works!");
end
I get the following exception, when I run the code:
Not enough input arguments.
Error in depsim (line 3)
ret = ones(a,b)
Error in test (line 28)
simulate = depsim;
I do not understand what the problem is, do I need to pass the handle differently?

 Accepted Answer

What appears in the error message is not what appears in the code you posted. First a comment about the code you posted:
simulate = @depsim;
g = @(x,y) fftest(x,y,@simulate);
As written this is probably not going to work. The first line defines a variable named simulate that contains a function handle. The second line treats simulate as a function and creates a function handle to it. If you wanted to pass the variable you created on the first line into fftest get rid of the second @ in the second line.
simulate = @depsim;
g = @(x,y) fftest(x,y,simulate);
Now from the error message:
Error in test (line 28)
simulate = depsim;
This does not have anything to do with function handles. This attempts to call the depsim function with 0 inputs and assign 1 output from that function call to the variable simulate. If you intended this to create a function handle to depsim, you need the @ before the function name.
simulate = @depsim;

1 Comment

Sy this is my fault, that was the output of an earlier execution.
Thank you, the second @ at simulate was the problem.

Sign in to comment.

More Answers (0)

Categories

Find more on Historical Contests in Help Center and File Exchange

Products

Release

R2019b

Asked:

on 6 Feb 2022

Edited:

on 6 Feb 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!