Wednesday, November 1, 2017

[Matlab GUI] Callback Definition and Anonymous function (Mathworks link)

Below is the Mathworks link on callback function and anonymous function.

1. Callback definition 
source link

Callback Definition

Ways to Specify Callbacks



To use callback properties, assign the callback code to the property. Use one of the following techniques:
  • A function handle that references the function to execute.
  • A cell array containing a function handle and additional arguments
  • A character vector that evaluates to a valid MATLAB® expression. MATLAB evaluates the character vector in the base workspace.
Defining a callback as a character vector is not recommended. The use of a function specified as function handle enables MATLAB to provide important information to your callback function.

Callback Function Syntax

Graphics callback functions must accept at least two input arguments:
  • The handle of the object whose callback is executing. Use this handle within your callback function to refer to the callback object.
  • The event data structure, which can be empty for some callbacks or contain specific information that is described in the property description for that object.
Whenever the callback executes as a result of the specific triggering action, MATLAB calls the callback function and passes these two arguments to the function .
For example, define a callback function called lineCallback for the lines created by the plot function. With the lineCallback function on the MATLAB path, use the @ operator to assign the function handle to the ButtonDownFcn property of each line created by plot.

plot(x,y,'ButtonDownFcn',@lineCallback)
Define the callback to accept two input arguments. Use the first argument to refer to the specific line whose callback is executing. Use this argument to set the line Color property:

function lineCallback(src,~)
   src.Color = 'red';
end

The second argument is empty for the ButtonDownFcn callback. The ~ character indicates that this argument is not used.

Passing Additional Input Arguments

To define additional input arguments for the callback function, add the arguments to the function definition, maintaining the correct order of the default arguments and the additional arguments:

function lineCallback(src,evt,arg1,arg2)
   src.Color = 'red';
   src.LineStyle = arg1;
   src.Marker = arg2;
end
Assign a cell array containing the function handle and the additional arguments to the property:

plot(x,y,'ButtonDownFcn',{@lineCallback,'--','*'})

You can use an anonymous function to pass additional arguments. For example:


plot(x,y,'ButtonDownFcn',...
    @(src,eventdata)lineCallback(src,eventdata,'--','*'))

Related Information

For information on using anonymous functions, see Anonymous Functions.
For information about using class methods as callbacks, see Class Methods for Graphics Callbacks.
For information on how MATLAB resolves multiple callback execution, see the BusyAction and Interruptible properties of the objects defining callbacks.

Define a Callback as a Default

You can assign a callback to the property of a specific object or you can define a default callback for all objects of that type.
To define a ButtonDownFcn for all line objects, set a default value on the root level.
  • Use the groot function to specify the root level of the object hierarchy.
  • Define a callback function that is on the MATLAB path.
  • Assign a function handle referencing this function to the defaultLineButtonDownFcn.

  • set(groot,'defaultLineButtonDownFcn',@lineCallback)

The default value remains assigned for the MATLAB session. You can make the default value assignment in your startup.m file.



2. Anonymous function



What Are Anonymous Functions?

An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle. Anonymous functions can accept inputs and return outputs, just as standard functions do. However, they can contain only a single executable statement.
For example, create a handle to an anonymous function that finds the square of a number:

sqr = @(x) x.^2;
Variable sqr is a function handle. The @ operator creates the handle, and the parentheses () immediately after the @ operator include the function input arguments. This anonymous function accepts a single input x, and implicitly returns a single output, an array the same size as x that contains the squared values.
Find the square of a particular value (5) by passing the value to the function handle, just as you would pass an input argument to a standard function.

a = sqr(5)
a =
   25
Many MATLAB® functions accept function handles as inputs so that you can evaluate functions over a range of values. You can create handles either for anonymous functions or for functions in program files. The benefit of using anonymous functions is that you do not have to edit and maintain a file for a function that requires only a brief definition.
For example, find the integral of the sqr function from 0 to 1 by passing the function handle to the integral function:

q = integral(sqr,0,1);
You do not need to create a variable in the workspace to store an anonymous function. Instead, you can create a temporary function handle within an expression, such as this call to the integral function:

q = integral(@(x) x.^2,0,1);

Variables in the Expression

Function handles can store not only an expression, but also variables that the expression requires for evaluation.
For example, create a function handle to an anonymous function that requires coefficients ab, and c.


a = 1.3;
b = .2;
c = 30;
parabola = @(x) a*x.^2 + b*x + c;

Because ab, and c are available at the time you create parabola, the function handle includes those values. The values persist within the function handle even if you clear the variables:


clear a b c
x = 1;
y = parabola(x)
y =
   31.5000
To supply different values for the coefficients, you must create a new function handle:


a = -3.9;
b = 52;
c = 0;
parabola = @(x) a*x.^2 + b*x + c;

x = 1;
y = parabola(1)

y =
   48.1000
You can save function handles and their associated values in a MAT-file and load them in a subsequent MATLAB session using the save and load functions, such as


save myfile.mat parabola

Use only explicit variables when constructing anonymous functions. If an anonymous function accesses any variable or nested function that is not explicitly referenced in the argument list or body, MATLAB throws an error when you invoke the function. Implicit variables and function calls are often encountered in the functions such as evalevalinassignin, and load.  Avoid using these functions in the body of anonymous functions.

Multiple Anonymous Functions

The expression in an anonymous function can include another anonymous function. This is useful for passing different parameters to a function that you are evaluating over a range of values. For example, you can solve the equation
for varying values of c by combining two anonymous functions:


g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));

Here is how to derive this statement:
  1. Write the integrand as an anonymous function,
    @(x) (x.^2 + c*x + 1)
    
  2. Evaluate the function from zero to one by passing the function handle to integral,
    integral(@(x) (x.^2 + c*x + 1),0,1)
    
  3. Supply the value for c by constructing an anonymous function for the entire equation,


    g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));
    
The final function allows you to solve the equation for any value of c. For example:

g(2)
ans =
   2.3333

Functions with No Inputs

If your function does not require any inputs, use empty parentheses when you define and call the anonymous function. For example:

t = @() datestr(now);
d = t()

d =
26-Jan-2012 15:11:47
Omitting the parentheses in the assignment statement creates another function handle, and does not execute the function:

d = t

d = 
    @() datestr(now)

Functions with Multiple Inputs or Outputs

Anonymous functions require that you explicitly specify the input arguments as you would for a standard function, separating multiple inputs with commas. For example, this function accepts two inputs, x and y:

myfunction = @(x,y) (x^2 + y^2 + x*y);

x = 1;
y = 10;
z = myfunction(x,y)

z = 111
However, you do not explicitly define output arguments when you create an anonymous function. If the expression in the function returns multiple outputs, then you can request them when you call the function. Enclose multiple output variables in square brackets.
For example, the ndgrid function can return as many outputs as the number of input vectors. This anonymous function that calls ndgrid can also return multiple outputs:

c = 10;
mygrid = @(x,y) ndgrid((-x:x/c:x),(-y:y/c:y));
[x,y] = mygrid(pi,2*pi);

You can use the output from mygrid to create a mesh or surface plot:

z = sin(x) + cos(y);
mesh(x,y,z)

Arrays of Anonymous Functions

Although most MATLAB fundamental data types support multidimensional arrays, function handles must be scalars (single elements). However, you can store multiple function handles using a cell array or structure array. The most common approach is to use a cell array, such as

f = {@(x)x.^2;
     @(y)y+10;
     @(x,y)x.^2+y+10};

When you create the cell array, keep in mind
that MATLAB interprets spaces as column separators. 
Either omit spaces from expressions, as shown in the previous code, 
or enclose expressions in parentheses, such as

f = {@(x) (x.^2);
     @(y) (y + 10);
     @(x,y) (x.^2 + y + 10)};

Access the contents of a cell using curly braces. 
For example, f{1} returns the first function handle. To execute the function, pass input values in parentheses after the curly braces:

x = 1;
y = 10;

f{1}(x)
f{2}(y)
f{3}(x,y)

ans =
     1

ans =
    20

ans =
    21

No comments:

Post a Comment