Passing a constant function handle to another function

2 ビュー (過去 30 日間)
Leo S
Leo S 2022 年 2 月 6 日
編集済み: Leo S 2022 年 2 月 6 日
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?

採用された回答

Steven Lord
Steven Lord 2022 年 2 月 6 日
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 件のコメント
Leo S
Leo S 2022 年 2 月 6 日
編集済み: Leo S 2022 年 2 月 6 日
Sy this is my fault, that was the output of an earlier execution.
Thank you, the second @ at simulate was the problem.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeHistorical Contests についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by