Flow of information in callback functions

1 view (last 30 days)
DB
DB on 16 Mar 2019
Commented: Rik on 16 Mar 2019
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.

Accepted Answer

Rik
Rik on 16 Mar 2019
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 Comments
DB
DB on 16 Mar 2019
Thanks, it clarifies a lot.
Rik
Rik on 16 Mar 2019
Your welcome. If my answer helped you, please consider marking it as accepted answer.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!