Intro to MATLAB Unit 3*: FUNCTIONS (Advanced)
Anonymous functions allow you to create functions without specifically defining them in a file. Anonymous functions are intended for extremely simple functions, as you only have one line to define an anonymous function. A sample anonymous function would look like:
fallingObjectAnon = @ (x) sqrt(2 * x / 9.81)
These anonymous functions make the link between computer programming functions and mathematical functions even more clear.
The name of the function is to the left of the equals sign. The "@" tells MATLAB that it is an anonymous function (actually that it is a function handle, see below). The input parameters are contained within parentheses, followed by the single line MATLAB expression defining the function. Using an anonymous function is just like using any other function:
fallingObjectAnon(5) fallingObjectAnon(10) fallingObjectAnon(100)
Anonymous functions can be used in the command window, script files, or even within other functions.
It is possible to have anonymous functions with more than one input parameter, however, they are only capable of having one output parameter:
pythagoras = @ (x,y) sqrt(x^2 + y^2) pythagoras(3,4) pythagoras(10, 20)
You can create function handles to named and anonymous functions. A function handle is a 'variable' storing the function. You can store multiple function handles in an array, and save and load them, as you would any other variable.
A function handle is a MATLAB data type that stores an association to a function. Indirectly calling a function enables you to invoke the function regardless of where you call it from. Typical uses of function handles include:
- Construct handles to functions defined inline instead of stored in a program file (anonymous functions, see above).
- Pass a function to another function (as 'variable').
- Specify callback functions. For example, a callback that responds to a UI event or interacts with data acquisition hardware.
- Fix certain variables in a function
Pass a function to integration or optimization functions (such as integral and fzero):
a = 0; b = 5; % compute the integral of the sin (exp) function q1 = integral(@sin,a,b) q2 = integral(@exp,a,b)
Fix a certain variable in a function:
% use add2scalars to add 10 to the input y1 = add2scalars(10,2); y2 = add2scalars(10,5); y3 = add2scalars(10,8); add10toScalar = @(x) add2scalars(10,x) y1 = add10toScalar(2) y2 = add10toScalar(5) y3 = add10toScalar(8) % check whether a variable is a function handle isa(add10toScalar,'function_handle') isa(@sin,'function_handle')
Function files may contain more than one function. When this occurs, the first function that appears at the top of the file is considered the primary function. All other functions contained within the file are subfunctions. Only the primary function can be called from the command window. The subfunctions may only be called within the function file. This again relates back to using functions as a way of organization.
[x, y] = trajectoryCalc(5) [x2, y2] = trajectoryCalc(100) h = maxHeight(5) h = maxHeight_nested(5) % <- this leads to an ERRROR!
Notice that the same thing can be accomplished without subfunctions by using the functions that we have already defined:
[x, y] = trajectoryCalc2(5) [x2, y2] = trajectoryCalc2(100)
The choice between the two different options presented is often a matter of personal preference as well as practicality. Is there any reason for you or other people to access a function outside of the context of the primary function? If yes, keep it separate, if no, make it a subfunction.
MATLAB passes variables call-by-value, that means a copy of the variables is passed to a function. Changing the variable inside the function does not change the variable outside!
In other programming languages, like C/C++, you can specify whether you want to call a function by value or by reference. If you use call-by-reference , you are passing a pointer (to a vlaue) to the function. If the variable changes during the function call, the value will also be changes outside the function (the pointer changed).
Notice the important distinction between the function definition and the actual USE of the function. The definition is general, it acts uniformly on an input that we don't know the value of. Calling the function specifies that value and provides a specific result. To mark this distinction, inputs and outputs are called parameters when used with the (general) function definition, but they are called arguments when their value is known.
Ordinarily, each MATLAB function has its own local variables , which are separate from those of other functions and from those of the base workspace.
Functions are very strict about what variables they can and cannot see. Last week when you were writing your first script you probably saw all of the variables you created showing up in the workspace. Functions cannot see any variables in your workspace. They can only see what is passed to them through their input and output arguments. Per default, variables are local to a function.
Example: Say you are working on some trajectory functions. You might think you could define the gravity variable in the workspace and call your functions:
g = 9.81; t = fallingObject1(5) % <- this will lead to an ERROR!
Since functions only examine variables that have been created within their scope, this will fail. The gravity variable will not make it to the computations within the functions.
Instead, gravity should be defined within the function:
t = fallingObject2(5)
The reason MATLAB doesn't allow workspace variables into your functions is to reduce mistakes. Think about what would happen if a function modified the gravity variable. It would be very easy to not notice this and continue forward with incorrect results. Declaring constants within a function can be redundant, but it is typically safer.
To share variables between funtions, use global variables . If you declare the particular variable name as global in every function, then they all share a single copy of that variable. Any change of value to that variable, in any function, is visible to all the functions that declare it as global.
global g g = 9.81; t = fallingObject3(5)
To share the values of a variable only by ONE function, use persistent variables. Persistent variables are local to the function in which they are declared; yet their values are retained in memory between calls to the function. Persistent variables are similar to global variables because the MATLAB software creates permanent storage for both. They differ from global variables in that persistent variables are known only to the function in which they are declared. This prevents persistent variables from being changed by other functions or from the MATLAB command line.
persistentDEMO() persistentDEMO() persistentDEMO() clear persistentDEMO % deletes the persistent variables of the function persistentDEMO1() % this function uses a 'different' persistent variable
Write anonymous functions for the following:
- Area of a circle
- Miles per gallon of a car (inputs: miles driven, gallons used)
- Area of a triangle (inputs: base and height)
Lecture notes for CSE200 (Fall 2015) at Washington University in St. Louis by Marion Neumann (based on materials from Doug Shook).