Functions are perhaps the most important tool for programming. They allow the programmer to define a specific action that (usually) takes in some data, does some processing, and returns a result, much like most math functions. Yet, no matter what the purpose of a function is, the "syntax" for defining and using a function is always the same. Here we discuss how to use and define functions in Matlab.
A function in Matlab is always written using the same (starting) syntax. This syntax can be captured in a "Design Pattern". Your job is to learn this pattern for future use (and tests). When learning, you can refer here for help.
Make sure you review the Topic on Commenting and Style to go along with this Design Pattern
Remember, as always, design patterns show you a "template" of the syntax/rules necessary to complete a generic goal. In this case, the basic format of any Matlab function file is described.
%
% function return_value = name_of_function( parameters )
%
% Author:
% Date:
% Partner:
% Course:
%
% Function : Name of Function
%
% Purpose : What task does the function accomplish
% or what does it compute
%
% Parameters : What values/types are expected as input?
%
% Return : What comes out of the function?
%
% Examples of Usage (say for a sort function):
%
% >> grades = [ 95 52 95 80 71 85 78 12 93 99 ];
% >> sorted_array = sort( array )
% ans =
% [ 12 52 71 78 80 85 93 95 95 99 ]
%
%
function return_value = name_of_function( parameters )
return_value = 0; % or other default value
% CODE
end % function
The "recipe" for a function (the function's code) is always stored in a ".m" file. In Matlab, there should only be one function per file.
Important: The name of the .m file and the function should be the same!
Here is an example of a function that computes the average of two numbers. It shows the use of a return value, two parameters, comments, and computation. This function would be saved with the name "average.m".
%
% Author: H. James de St. Germain
% etc....
%
function avg = average(first_value, second_value)
avg = (first_value + second_value) / 2.0;
end % function
The very first thing you see in every function file (after the comments) is the line with the keyword function on it. This line is called the function "prototype" or "declaration".
%
% Header Comment
%
function avg = average(first_value, second_value) % Prototype / Declaration
It is important to know that this line Doesn't Do Anything! In other words, this line is a syntactic pattern that tells Matlab important information about the function. The line is never executed in your program, and can be considered a "Dummy" Statement, meaning not really part of the function.
Think of it this way, the function prototype is like the Cover of a book, it shows you the title, the author, maybe tells you a comment about the book, but if removed the book still contains the important parts of the book (the text).
Thus the function prototype is a means for telling Matlab that the M file contains a function (not a script) and what the name of the function is, what its return variable is called, and what parameters it takes. When the function is called (run by the computer), the computer starts at the first line of code following the prototype.
In the average function above, the first actual line of the function is:
avg = (first_value + second_value) / 2.0;
function | keyword function |
return_value | Optional: the name of a variable who's value is returned from function With multiple return values, we put the return value names in side square brackets. (e.g., function [name, date, address] = ask_for_personal_info()) |
= | The equals sign. Required with a return variable (see above) |
name | The name of the function (hopefully descriptive) for example sin, or tan, or length... |
'(' | Open parenthesis |
parameters | ZERO or more variables for which data is COPIED into the function. |
')' | Closing parenthesis |
CODE | The code specific to the function |
end | The key word end, specifying the end of the functions code |
Again, a function declaration is always of the form:
function result = name(parameters)
function - the key word function starts every function declaration.
name - a symbolic name telling the user of the function the purpose of the function. In the case above, the name is average.
parameters - symbolic names for the inputs to the function (the data the function will process to compute an answer.
In the case above, the parameters are named "first_value" and "second_value"
Inside the function are computations and an assignment of the result(s).
Calculation - Code to compute a value. In the above case the average value of the two input parameters is computed.
Output/Result variable - This is the symbolic name for the variable which will contain the result of all the work of the function. In the above case, the result variable is "avg". Whatever value is in the variable "avg" when the function ends, is "returned" to the caller of the function.
Functions should (almost) never contain the fprintf command. If you want to print the output of a function, then you should:
Call the function and assign the value to a variable.
Call the print the value of the variable.
Example
grade(1) = 87;
grade(2) = 95;
average_grade = average( grade(1), grade(2) );
fprintf('the average of the grades %f and %f is %f'\n', ...
grade(1), grade(2), average_grade);
The rare exception to the "do not print" rule is when a function is specifically written to provide user interaction, such as requesting input from the user or writing messages to the screen.
OUTSIDE: From the outside of a function (i.e., the command line or another function), we can use any variable names or "hard coded" values that we want. Inside the function, these values will be assigned the same Symbolic Name no matter what they were called outside of the function.
>> x = 20;
>> y = 10;
>> z = average(x,y);
>> z = average(200,100);
>> z = average(x,12);
>> w = average(average(5,10), x);
The following examples show several variations on functions, including those that return a single value, return no values, return many values, take parameters, take no parameters, etc.
function return_value = name( parameters )
CODE
end % function
function name( parameters )
CODE
end % end of function
function [value_1, value_2, value_3] = name( parameters )
CODE
end % end of function
Sometimes a function will just "do an action" but not based on anything the user wants. Such a function would be said to be "hard coded" and do the same thing every time. For example, the random function in most languages will return a random number but does not require any actual parameters to make it work.
function result = name()
CODE
end %end of function
The following comment design patterns show what a "industrial" product comments might look like. They are "overkill" for our class projects, but are worth a quick look.
Everything that is IN ALL CAPS must be replaced by the programmer to be specific to the current function.
Complete function description comment at the top of the file
Note, please remove (or modify) everything in ( ALL CAPS LANGUAGE ) below. (also remove the extra ()s).
%
% ( RETURN_VARIABLE = FUNCTION_NAME(PARAMETER_1, PARAMETER_2, ETC) )
%
% Author: YOUR FULL NAME AND CADE EMAIL ADDRESS
% Date: THE CURRENT DATE
% Partner: THE FULL NAME AND CADE EMAIL ADDRESS OF ANYONE YOU WORKED WITH
% Course: Computer Science 1000
%
% Function Description:
%
% ( THIS FUNCTION DOES THE FOLLOWING (WRITE WHAT THE SPECIFIC GOAL OF THIS
% SINGLE FUNCTION IS (_NOT_ WHAT THE GOAL OF THE ENTIRE PROGRAM IS). THIS
% DESCRIPTION SHOULD BE IN HIGH LEVEL ENGLISH AND MAY CONTAIN A LIST OF
% STEPS (E.G.,:
% 1) DO THIS
% 2) THEN DO THIS
% 3) CALCULATE THAT
% 4) RETURN THE FINAL VALUE AS RETURN_VARIABLE)
% )
%
%
% Input Parameters: (LIST ALL THE PARAMETERS TO THE FUNCTION (OR SAY
% NONE IF THERE ARE NO INPUT PARAMETERS)
%
% PARAMETER_1: Name, Type, Purpose
% PARAMETER_2: Name, Type, Purpose
% PARAMETER_3: Name, Type, Purpose
% ETC
%
% Returned Value: (LIST THE DATA THAT IS _RETURNED_ BY THIS FUNCTION.
% PLEASE NOTE THAT DATA PRINTED TO THE SCREEN IS _NOT_
% RETURNED. THERE IS A SPECIFIC DIFFERENCE BETWEEN
% THINGS PRINTED TO THE SCREEN AND THOSE RETURNED )
%
% Returned_Variable_1: Name, Type, Purpose
% ETC
%
% Algorithm: (ADD ANY ADDITIONAL NOTES YOU HAVE ABOUT THE FUNCTION
% HERE, INCLUDING HOW THE DATA IS PROCESSED OR WHAT
% KIND OF DATA STRUCTURES YOU MAY USE)
%
%
% Examples of Use:
%
% (SHOW HOW TO CALL THE FUNCTION)
%
% Here we begin by writing the function Prototype
function RETURN_VARIABLE = FUNCTION_NAME(PARAMETER_1, PARAMETER_2, ETC)
% Here we check that the actual number of args that the user gives when
% calling this function are equal to what the function expects.
if (nargin() ~= NUMBER)
error('must have NUMBER args (MORE INFORMATION HERE)');
end
% Now we start Implementing the algorithm
LOCAL_VARIABLES = ....;
% Set the RETURN_VARIABLE so that data goes back to the caller
RETURN_VARIABLE = SOME VALUE(s) CALCUALTED IN THE FUNCTION
end % function
%
% aprox_value_of_pi = approximate_pi( steps_to_take )
%
% Author: H. James de St. Germain
% Date: Oct 1, 2005
% Partner: I worked alone on this program
% Course: Computer Science 1000
%
% Function Description:
%
% This program approximates the value of pi by expanding a
% mathematical series.
%
% Input Parameters:
%
% steps_to_take: (integer number) how close an
% approximation to make.
%
% Returned Value:
%
% aprox_value_of_pi: (floating point number) This
% value will be some approximation of pi. The
% more steps, the closer the approximation.
%
% Algorithm:
%
% The series of interest is:
%
% 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ....
%
% At each step, 4 is divided by the next odd number. Then this
% value is alternatively subtracted and then added.
%
%
% Example of Use:
%
% >> approximate_pi( 1 )
% ans =
% 4
%
function aprox_value_of_pi = approximate_pi( steps_to_take )
if (nargin() ~= 1)
error('Usage: approximate_pi(steps_to_take)');
end
aprox_value_of_pi = 4;
time_to_subtract = true;
for i = 2:steps_to_take
if (time_to_subtract)
aprox_value_of_pi = aprox_value_of_pi - (4 / ((2*i)-1));
else
aprox_value_of_pi = aprox_value_of_pi + (4 / ((2*i)-1));
end
time_to_subtract = ~ time_to_subtract;
end % for loop
end % function