Is it possible to assign the constant value of a function handle to a variable?

8 ビュー (過去 30 日間)
Hello,
My program can sometimes generate this function handle:
g = @() 1.0
Or generally: g = @() c , c: constant
Is it possible to transfer that constant into a variable B, so that B = c?
Thanks.
Edit: Is it possible to check whether a function_handle has no inputs(@())?

採用された回答

Star Strider
Star Strider 2019 年 2 月 19 日
If you want to use the feval (link) function, yes:
g = @() 1;
B = feval(g)
producing:
B =
1
There may also be other ways to evaluate a function that does not accept an argument.
  2 件のコメント
Panagiotis Panagopoulos Papageorgiou
Panagiotis Panagopoulos Papageorgiou 2019 年 2 月 19 日
It works, thank you :)
By the way, is it possible to check if the space between the parentheses of a function handle(@()) is blank with an if statement?
Star Strider
Star Strider 2019 年 2 月 19 日
As always, my pleasure!
I doubt it. When I tried:
g = @() 1;
B = g()
this also worked, producing:
B =
1
however, this:
B = g(1)
produced:
Too many input arguments.
So perhaps you could use a try,catch (link) block to detect those.

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

その他の回答 (1 件)

Guillaume
Guillaume 2019 年 2 月 19 日
You don't need to use feval to invoke a function handle with no inputs, just use some empty brackets to make it clear you want to call it and not just copy the handle:
f = @() 0.5;
n = f()
To know the number of inputs of any functions (not just function handles), use nargin:
f = @() 0.5;
g = @(x) x;
>> nargin(f)
ans =
0
>> nargin(g)
ans =
1

カテゴリ

Help Center および File ExchangeProgramming Utilities についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by