Flow of information in callback functions

1 回表示 (過去 30 日間)
DB
DB 2019 年 3 月 16 日
コメント済み: Rik 2019 年 3 月 16 日
I am using a 3rd party optimization solver which comes with examples and I am trying to understand it. An example in it uses callback functions in these formats.
% The callback functions.
funcs.f1 = @(x) x(1)*x(4)*sum(x(1:3)) + x(3);
funcs.f2 = @f2;
funcs.f3 = @() sparse(ones(2,4));
where
function g = f2 (x)
g=f(x)% g is some function of x
end
And it is run as
[x] = solver(x0,funcs);
where x is the output vector of variables.
I am having trouble understanding the difference between flow of information in the 3 formats of the callback functions in the funcs struct.
1. In the funcs.f1, @(x) tells that it is a function with x as variables, right?
2. What does @f2 in funcs.f2 mean? Is the output g of the function f2 being passed in this format to funcs.f2?
3. And does @() in funcs.f3 mean that it is not the function of variable x and hence the input argument to @() is blank?
I would appreciate if someone would help.

採用された回答

Rik
Rik 2019 年 3 月 16 日
You can find some more information in the documentation.
The @ creates a function handle. There are two options here: an anonymous function, or a normal function handle.
The f1 statement creates an anonymous function with a single input. Any time you call it, it will run as if the x is replaced by your input variable, and all other variables are the same as before.
n=1;
f1=@(x) x+n;
n=2;
v=-1;
f1(v)%returns 0 because it uses the old value of n
The f2 statement creates a function handle. When you run it, Matlab will look for that function on the search path. You can use it in functions like accumarray where you need to input a function handle (or you could even use it to shorten function names).
f2=@mean;
f2([1 2 3])%returns 2, same as mean([1 2 3]) would
The f3 statement creates an anonymous function without an input. Like any function this can have any number of output arguments.
f3=@() disp('next round..')
for n=1:3
trigger_boxing_bell_function
f3();
end
Hope this helps.
  2 件のコメント
DB
DB 2019 年 3 月 16 日
Thanks, it clarifies a lot.
Rik
Rik 2019 年 3 月 16 日
Your welcome. If my answer helped you, please consider marking it as accepted answer.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by