Chapter 6
Attaway MATLAB 4E
MATLAB Programs
Chapter 6 Attaway MATLAB 4E Types of Functions Categories of - - PowerPoint PPT Presentation
MATLAB Programs Chapter 6 Attaway MATLAB 4E Types of Functions Categories of functions: functions that calculate and return one value functions that calculate and return more than one value functions that just accomplish a task, such
Attaway MATLAB 4E
MATLAB Programs
Categories of functions:
functions that calculate and return one value functions that calculate and return more than one value functions that just accomplish a task, such as printing,
without returning any values
They are different in:
the way they are called what the function header looks like
All are stored in code files with the extension .m
All function definitions consist of:
The function header
The reserved word function Output arguments and the assignment operator (only if the
function returns value(s)
Function name and input arguments
A block comment describing the function The body of the function which includes all statements,
including putting values in all output arguments, if there are any
end
General form of a function that returns more than one
The output arguments are separated by commas
function [output arguments] = functionname(input arguments) % Comment describing the function Statements here; these must include putting values in all
end functionname.m
For example, if the function header is:
function [x,y,z] = fnname(a,b)
This indicates that the function is returning 3 things, so a
call to the function might be (assuming a and b are numbers):
[g,h,t] = fnname(11, 4.3);
Or using the same names as the output arguments (it
doesn’t matter since the workspace is not shared):
[x,y,z] = fnname(11, 4.3);
This function call would only get the first value returned:
result = fnname(11, 4.3);
function [ranx, rany] = tworan ranx = randi([10,20]); rany = randi([10,20]); end
tworan.m Example Function call: [x, y] = tworan
function [ranx, rany] = tworanb(a,b) ranx = randi([a,b]); rany = randi([a,b]); end
tworanb.m Example Function call: [x, y] = tworanb(5, 50)
A function that does not return anything has no
The statements in the body would typically display or
function functionname(input arguments) % Comment describing the function statements here end
functionname.m
Since no value is returned, the call to such a function is
For example, if this is the function header:
function fnname(x,y)
A call to the function might look like this:
fnname(x,y)
This would NOT be a valid call; since the function is
result = fnname(x,y); % Invalid!
prttworan.m Example Function call: prttworan
function prttworanb(a,b) fprintf(One is %d\n, randi([a,b])) fprintf(The other is %d\n, randi([a,b])) end
prttworanb.m Function call: prttworanb(5,50)
You do not always have to have input arguments to a function. If
you do not, you can have (both in the function header and in the function call) empty (), or you can just leave them out
The function header and function call have to match up:
the name has to be the same the number of input arguments must be the same the number of variables in the left-hand side of the assignment
should be the same as the number of output arguments
if there are no output arguments, the function call is a statement
Functions that return values do not normally print them, also –
that is left to the calling function/script
In a modular program, every task is implemented in a
In MATLAB, a program generally consists of a script
At the very least, most MATLAB programs consist of a
get the input calculate results display the results
When one function calls another, the two functions can be stored in
the same code file with the same name as the primary function
The subfunction can only be called by the primary
primary function header primary function body includes call to subfunction end subfunction header subfunction body end
primary.m
In a modular program, a script calls functions Given the following script (where x,y,z are 3 things)
[x,y,z] = getinputs; result = calcstuff(x,y,z); displayit(x,y,z, result)
With just that information, we can write the
function [x,y,z] = getinputs function result = calcstuff(x,y,z) function displayit(x,y,z, result)
The scope of any variable is the workspace in which it
The workspace created in the Command Window is
Scripts also create variables in the base workspace
That means that variables created in the Command
Window can be used in scripts and vice versa
However, that is very poor programming style
Variables defined in functions, however, are local to
Persistent variables are used only within functions For normal variables in functions, memory is allocated when
the function is invoked and then released when the function stops executing
With persistent variables, the memory stays allocated and the
value remains in that location
The variable has to be declared as persistent Normally, an if statement is used to check to see if it is empty
and if so initializes to a value
A counter is a good example: counts how many times the
function is called
clear functions will reset all persistent variables clear fnname will reset persistent variables in fnname
% This script demonstrates persistent variables % The first function has a variable "count" fprintf('This is what happens with a "normal" variable:\n') func1 func1 % The second fn has a persistent variable "count" fprintf('\nThis is what happens with a persistent variable:\n') func2 func2 function func1 % This fn increments a variable "count" count = 0; count = count + 1; fprintf('The value of count is %d\n',count) end
persistex.m func1.m
function func2 % This fn increments a persistent variable "count" persistent count if isempty(count) count = 0; end count = count + 1; fprintf('The value of count is %d\n',count) end
func2.m
Syntax errors: mistakes in language e.g. missing quote
Run-time (or execution-time) errors: errors that are
Logical errors: mistakes in reasoning e.g. using an
There are several methods that can be used to find
Tracing: using the echo statement which will show all
statements as executed
Using MATLABs Editor/Debugger Set breakpoints so values of variables/expressions can be
examined at various points
dbstop sets a breakpoint dbcont continues execution dbquit quits debug mode
Function stubs can be used to prevent bugs in the first
The procedure is:
Put the main program script in place with all function
calls
Create code files for all functions, which consist solely of
the correct function header and a dummy body that mimics what the function will eventually do (e.g. return
Then, one by one fill in the actual function bodies
The lump sum S to be paid when interest on a loan is compounded annually is given by S = P(1 + i)n where P is the principal invested, i is the interest rate and n is the number of
increases through the years from 1 to n. The main script will call a function to prompt the user for the number of years (and error-check to make sure that the user enters a positive integer). The script will then call a function that will plot S for years 1 through n. It will use .05 for the interest rate and $10,000 for P. For now we will write just the script and function stubs.
% Plots the amount of money in an account % after n years at interest rate i with a % principal p invested % Call a function to prompt for n n = promptyear; % Call a function to plot plots(n, .05, 10000)
function outn = promptyear
end function plots(n, i, p) plot(n, i*p) end Note that the function stubs are somewhat nonsensical – BUT – they mimic what the functions will eventually do. The promptyear function will eventually return an integer, and the plots function will eventually plot something. Using the values of n, i, and p ensures they were passed correctly.
Live scripts are created using the Live Editor Can embed equations, images, formatted text, and
Equations are created using LaTex notation Plots are shown in the live script instead of in separate
Live scripts are stored in .mlx files Can be converted to PDF or HTML format
Code in scripts can be broken into sections called code
You can run one code cell at a time Code cells are created with comments that start with
Code in code cells can also be published in HTML
Do this from the Publish tab in the Editor
Not matching up arguments in a function call with the
Not having enough variables in an assignment
Attempting to call a function that does not return a
Forgetting that persistent variables are updated every
If arguments are passed to a function in the function
Functions that calculate and return value(s) will not
Functions should not normally be longer than one
Do not declare variables in the Command Window
Pass all values to be used in functions to input