2013
Anonymous Functions
Anonymous Functions: Simple one-line functions that are called using their function handle. It does not have to be stored in an M-file. Anonymous functions can be created in the Command Window or in any script. The syntax for an anonymous function is:
fhandle = @(arguments) functionbody
Function handle is a way of referring to a function. The handle is assigned to this name using the @ operator.
Copyright 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Anonymous Functions
If no argument is passed to an anonymous function, the parenthesis must still be in the function definition and in the function call. Example: an anonymous function that prints a random real number with two decimal places:
>> prtran = @ () fprintf('%.2f\n',rand); >> prtran() 0.95
Copyright 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The function is called using the handle and passing arguments to it:
>> cirarea(4) ans = 50.2655 >> cirarea(1:4) ans = 3.1416 12.5664 28.2743 50.2655
Copyright 2013 Pearson Educati on, Inc. Publishing as Pearson Addison-Wesley
The @ operator gets the handle of the function, which is then stored in a variable facth. Handle could be used to call the function instead of the name of the function itself.
facth(5)
Copyright 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
03.05.2013
Function Functions
One reason for using function handles is to be able to pass functions to other functions these are called function functions. In other words they are functions whose input arguments include the names of other functions. The functions that are passed to the function function are normally used during that functions execution.