CS 211 Lesson 12
User-defined Functions and Arguments
Quote:
"Opportunities are usually disguised as hard work, so most people don't recognize them." Ann Landers
Lesson Objectives:
Understand the benefits of creating user-defined functions
Understand the role of user-defined functions in program design
Understand the difference between MATLAB functions and scripts
Know the format of a user-defined function
Understand the difference between actual arguments and dummy arguments
Be able to create and use simple functions
Lesson:
I. MATLAB Concepts
A. User Defined Functions
Most non-trivial programs are written as a set of independent functions because:
Breaking a large problem into smaller sub-problems (called top-down design) makes problem solving easier.
Duplicate code can be eliminated and consolidated into a single function.
Isolating the number of places a variable can change simplifies debugging.
MATLAB functions versus scripts
Functions Scripts Functions have their own separate workspace. Scripts use the global workspace. Variables created outside a function's workspace are not accessible to other functions. All variables in the global workspace are accessible to all scripts. Functions communicate with other functions by using input arguments and output arguments (also called parameters). Scripts communicate with other scripts by modifying global variables. Functions should always be used for large program development. Scripts are OK for small interactive tasks, but never use scripts for large programs. A side-effect occurs when a variable's value is changed unintentionally.
When two different scripts use the same variable name, they are manipulating a single variable stored in the global memory workspace.
When two different functions use the same variable name, they are manipulating two totally different memory locations, each in a separate workspace.
Side-effects are bad because they make debugging very difficult.
Functions minimize side-effects, which is very good!
Scripts create ideal conditions for side-effects to happen, which is very bad!B. DEFINING user-defined functions
User-defined functions must be defined before they can be used.
The general syntax for defining a function is
function [output_argument_list] = Function_name ( input_argument_list )
% one or more statements
end
The following is an example of a function definition:
function [Low, High] = High_Low(First, Second)
if First < Second
Low = First;
High = Second;
else
Low = Second;
High = First;
end
end % function High_LowIn the above example
The function's name is High_Low
The function's dummy input arguments are First and Second
The function's dummy output arguments are Low and High
Functions may have zero or more input arguments and zero or more output arguments.
If a function has zero input arguments, the parentheses may be omitted - but you should include them because it is good programming style.
If a function has more than one input argument, the arguments must be separated by commas.
If a function has zero output arguments, the equals sign is omitted (as is the output argument list).
If a function has one output argument, the square brackets may be (and usually are) omitted.
If a function has more than one output argument, they are enclosed in square brackets and separated by commas.
You should end all function definitions with an end statement and a comment indicating it is the end of the function.
Input and output arguments used in the function definition are called dummy arguments. You can think of the arguments as being "dumb" because they do not have an actual value until the function is called.
The following examples are all user-defined functions and each is defined in its own m-file.
Example User Defined Function Number of input arguments Number of output arguments Wait_For_Enter 0 0 New_Lines 1 0 Current_Time 0 1 DegF_To_DegC 1 1 Point_Distance multiple (4) 1 Min_Max_N 1 multiple (4) C. USING user-defined functions
User-defined functions are called (used) in the same way as MATLAB's built-in functions.
The general syntax for calling (using) a function is based on the function's input and output arguments, as shown below:
Function_name() % no input arguments
% no output argumentsFunction_name( input_argument_list ) % one or more input arguments
% no output argumentsoutput_argument = Function_name ( input_argument_list ) % one or more input arguments
% one output argument[output_argument_list] = Function_name ( input_argument_list ) % one or more input arguments
% more than one output arguments
The input and output arguments used when a function is called are called actual arguments.
When a function is called, the following happens:
The values of the actual input arguments are assigned to the dummy input arguments (according to their order).
The statements in the function are executed until the end of the function is reached (or a return statement is executed).
The values of the dummy output arguments are assigned to the actual output arguments (according to their order).
For example, the sample calls below illustrate various combinations of input and output arguments.
[Smaller, Larger] = High_Low(Number1, Number2);
[Less, More] = High_Low(A, B);
[Little, Big] = High_Low(Value1, Value2);
Wait_For_Enter();
New_Lines(5);
now = Current_Time();
Celsius = DegF_To_DegC(Fahrenheit);
Distance1 = Point_Distance(3, 5, -2, 4);
Distance2 = Point_Distance(5, 7, 6, 1);
[Min_value Max_value Num_values] = Min_Max_N(Matrix);
[Min Max Num] = Min_Max_N(rand(4,5));
From these examples, note that:
The number of actual input arguments must match the number of dummy input arguments.
The actual arguments do not have to have the same names as their corresponding dummy arguments. This allows a function to be called with different values each time and return different values each time.
The correspondence between actual and dummy arguments is based on their ordering.
If there are fewer actual output arguments than dummy output arguments, then the additional dummy output arguments are not copied back to actual arguments. For example, consider the code
Result = High_Low(Number1, Number2)
This call will copy the final value of Low to Result and ignore the value of High.
The following example program demonstrates how to call the example functions defined above:
II. Good Programming Practices
To distinguish between the use of variables and "functions
with no inputs", place parentheses after all function calls, even those that
do not have input arguments. For example:
clc
% a function call with no inputs - bad style.
clc() %
good style - you immediately know this is a function call.
x = Alpha;
% is Alpha a function call or a variable? If you have used good style, it is
a variable.
x = Alpha();
% x gets its value from the function call to Alpha; Alpha must be a function
call, and not a variable, because of the parentheses.
Always include an end
statement after the last statement of your function and include a comment
with the function's name, as in
end % function High_Low
Always include a full comment header block with each function. This documentation is critical when you are developing large programming projects. For the INPUTS section of the comment header block, list every input argument and give a brief description of each one. For the OUTPUTS section, list every output argument and give a brief description of each one. Refer to the example function files linked above for specific examples. One example is shown below:
function Distance = point_distance(x1, y1, x2, y2) %--------------------------------------------------------------- % USAGE: Distance = point_distance(x1, y1, x2, y2) % % AUTHOR: Col David S. Gibson DATE: 21 Sep 04 % MODIFIED: Dr. Wayne Brown DATE: 16 Aug 05 % % DESCRIPTION: This function returns the Cartesian distance % between the two points (x1, y1) and (x2, y2) % % INPUTS: x1 - x coordinate of first point % y1 - y coordinate of first point % x2 - x coordinate of second point % y2 - y coordinate of second point % % OUTPUTS: Distance - Cartesian distance between (x1,y1) & (x2,y2) % % REFERENCES: None %---------------------------------------------------------------
Always use good descriptive variable names for all dummy input argument names, all dummy output argument names, and all local function variable names.
III. Algorithms
(None for this lesson)
Lab Work: Lab 12
References: Chapman Textbook: section 5.1-5.2