Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2017
Outline
Scripts and Functions
Algorithms
Analgorithmisthesequenceofstepsneededtosolvea problem
Top-downdesignapproachtoprogramming:breakasolution into steps, then further refine each one
Genericalgorithmformanyprograms:
1. Get the input
2. Calculate result(s) 3. Display the result(s)
Amodularprogramwouldconsistoffunctionsthatimplement each step
Scripts
ScriptsarefilesinMATLABthatcontainasequenceofMATLAB instructions, implementing an algorithm
Scriptsareinterpreted,andarestoredinM-files(fileswiththe extension .m)
ScriptM-filescontaincommandstobeexecutedasthoughthey were typed into the command window, i.e., they collect many commands together into a single file
Tocreateascript,clickon“NewScript”undertheHOMEtab; this opens the Editor
Onceascripthasbeencreatedandsaved,itisexecutedby entering its name at the prompt
thetypecommandcanbeusedtodisplayascriptinthe Command Window
Documentation
Scriptsshouldalwaysbedocumentedusingcomments
Commentsareusedtodescribewhatthescriptdoes,andhowit
accomplishes its task
CommentsareignoredbyMATLAB
Commentsareanythingafterthecharacter%totheendofthat line; longer comment blocks are contained in between %{ and %}
Inparticular,thefirstcommentlineinascriptiscalledtheH1 line; it is what is displayed with help
Scripts with I/O
GeneraloutlineofascriptwithI/O:
1. Prompt the user for the input (use input function)
2. Calculate values based on the input
3. Print everything in a formatted way using fprintf
(Normally, print both the input and the calculated values)
Usesemicolonsthroughoutsothatyoucontrolexactly what the execution of the script looks like
fprintf : summary & examples
fprintf(’format_specs’, variables);
format_specs – print format specifications
variables – list of variables, arrays, or matrices to be printed
Differentwaystoprint100*pi
» fprintf(’%10.6f\n’, 100*pi) » fprintf(’%+10.6f\n’, 100*pi) » fprintf(’%10.0f\n’, 100*pi) » fprintf(’%#10.0f\n’, 100*pi) » fprintf(’%010.0f\n’, 100*pi) 314.159265
+314.159265
314
314.
0000000314
fprintf : summary & examples
Otherformatting:
\n – newline character
\t – tab character
\\ – to print one slash
” – to print one single quote
Remark:Printingvectorsandmatrices:usuallyeasierwithdisp
fprintf : Examples
Expressionsaftertheformatstringfillinfortheplaceholders,insequence
» fprintf(’The numbers are %4d and %.1f\n’, 3, 24.59) The numbers are 3 and 24.6
» x = [5 10 15];
» fprintf(’x = %5.2f, x^2 = %6.2f\n’,[x; x.^2]); % vectorized form of fprintf
x = 5.00, x^2 = 25.00
x = 10.00, x^2 = 100.00
x = 15.00, x^2 = 225.00
Itisnotthecasethateveryfprintfstatementprintsaseparateline;linesare controlled by printing \n;
example from a script:
would print
fprintf(’Hello and’)
fprintf(’ how \n\n are you?\n’)
Hello and how
are you?
Script
Thetargetheartrate(THR)forarelativelyactivepersonisgivenby THR = (220 − A) ∗ 0.6 where A is the person’s age in years
Wewantascript(thrscript.m)thatwillpromptfortheage,then calculate and print the THR.
% Calculates a person’s target heart rate
age = input(’Please enter your age in years: ’); thr = (220-age) * 0.6;
fprintf(’For a person %d years old,\n’, age) fprintf(’the target heart rate is %.1f.\n’, thr)
Executingthescriptwouldlooklikethis:
» thrscript
Please enter your age in years: 33
For a person 33 years old,
the target heart rate is 112.2.
»
Notethattheoutputissuppressedfrombothassignmentstatements.Theformat of the output is controlled by the fprintf statements
User-Defined Functions
User-definedfunctions,orfunctionM-filesmuststartwitha function definition line, and may accept input variables and/or return output variables
Usingtheuser-definedfunctionworksjustlikeusinga built-in function: you call it by giving the function name and passing argument(s) to it in parentheses; that sends control to the function which uses the argument(s) to calculate the result – which is then returned
General form of function definition
function output = fname(input)
% Comments
statements to calculate some value(s) output = some values
end
Thedefinitionincludes:
the function header (the first line)
the function body (everything else) Theheaderofthefunctionincludes:
The reserved word function
The name of an output argument, followed by the assignment
operator “=”
The function name fname which is arbitrary and must match the
name of the M-file, i.e., fname.m
The input argument correspond with the value that is passed to
the function when called
Function Example
afunctionthatcalculatesandreturnstheareaofacircle
There would be one input argument: the radius
There would be one output argument: the area
To be saved in an M-file called get_area.m:
function area = get_area(radius)
% This function calculates the area of a circle
area = pi * radius^2;
end
Puttingavalueintheoutputargumentishowthefunctionreturnsthevalue;in this case, with an assignment statement.
Tocallthefunction
» get_area(4)
ans =
50.2655
» myarea = get_area(5);
» disp(myarea);
78.5398
» r = 4.5
» fprintf(’The area of a circle with radius %5.2f is %8.4f\n’, r, get_area(r));
The area of a circle with radius 4.50 is 63.6173
Function Example
Ifone/severalinputargumentsmaybevectorsormatrices,use the right operators !
In the expression area = pi * radius^2, the variable radius can’t be a vector (why ?)
Tofixit,wemustchange^to.^,so Callexample:
area = pi * radius.^2;
» r = [2 3 4];
» get_area(r)
ans =
12.5664 28.2743 50.2655
» fprintf(’The area of a circle with radius %4.1f is %8.4f\n’, [r; get_area(r)])
The area of a circle with radius 2.0 is 12.5664
The area of a circle with radius 3.0 is 28.2743
The area of a circle with radius 4.0 is 50.2655
Multi-Input Multi-Output Functions
Ingeneral,afunctioncanacceptseveral(ornoone)variablesasinput arguments and produce several (or no one) variables as outputs.
Theinputargumentsareseparatedbycommas,andtheoutput variables are listed within brackets, and can have different sizes and types:
Theinputargumentscorrespondone-to-onewiththevaluesthatare passed to the function when called.
Example:
function [out1, out2, …] = fname(in1, in2, …)
function[m1, m2, cv] = my_stats(x, y)
% For two vectors x and y, calculate the mean of x in m1,
% the mean of y in m2 and the covariance between x and y
% in cv
m1 = mean(x);
m2 = mean(y);
cv = cov(x, y);
end
Function Example
function [r,m] = rms(x)
% file rms.m calculates
% the root-mean-square (RMS) value
% and the mean-absolute value of a vector x:
r = sqrt(sum(abs(x).^2) / length(x));
m = sum(abs(x)) / length(x);
end
Function Example
No input arguments
function a = gen_rnd_matrix()
% Generate a random square matrix of dimension n
n = input(’Enter the matrix dimension: ’);
a = rand(n);
end
» b = gen_rnd_matrix
Enter the matrix dimension: 2 b=
0.77905 0.90372
0.71504 0.89092
No output
function repeat(n)
% print n times the string ’—–’
for i = 1:n
fprintf(’—–\n’);
end end
» repeat(3);
—–
—–
—–
MATLAB Program
Ascript(storedinanM-file)whichcallsone/severaluser-defined function(s) (also stored in M-files) is called a program
Example:thefollowingprogramwillprompttheuserfortheradii (the inner radius Ri and the outer radius Ro of a hollow sphere), will call a function to calculate the volume of the hollow sphere, and will print the result.
The volume of a hollow sphere is given by 4π (Ro3 − Ri3) 3
Program example
volume_hol_sphere.m file
% This script calculates the volume of a hollow
sphere
inner = input(’Enter the inner radius: ’);
outer = input(’Enter the outer radius: ’);
volume = get_volume(inner, outer); fprintf(’The volume is %.2f\n’, volume)
get_volume.m file
function hollvol = get_volume(inner, outer)
% Calculates the volume of a hollow sphere
hollvol = 4/3 * pi * (outer^3 – inner^3);
end
Scope and workspace
AworkspaceisaMATLABplacecreatedtostorevariables
TheworkspacecreatedintheCommandWindowiscalledthe
base workspace
All the variables defined by the user from command prompt (») are stored in the base workspace
These variables are listed in the Workspace window
Thescopeofanyvariableistheworkspacetowhichisbelongs.
Thescriptsalsocreatevariablesinthebaseworkspace
That means that variables created in the Command Window can be used in scripts and vice versa
Thefunctionscreatetheirownworkspace
When a function is called, its new created workspace will contain the following variables: input arguments, output arguments, and all local variables (defined in the function body)
After the function return, its workspace is destroyed and all variables are lost !
Share data between workspaces
Generalrules(themostsecureway):
If a function need to “know” the value of an existing variable (from a given workspace), pass it as an input argument to the function
If a function must change the value of an existing variable, use an output argument to assign the new value
% increment.m file
function [a] = increment(x, step)
fprintf(’[increment call] x = %5.2f and step = %2d\n’, x, step); a = x + step;
step = step + 1; % local variable ’step’ was changed fprintf(’[increment call] x = %5.2f and step = %2d\n’, x, step);
end
% test.m script
x = 3.1; step = 2;
fprintf(’[base workspace] x = %5.2f and step = %2d\n’, x, step); x = increment(x, step);
fprintf(’[base workspace] x = %5.2f and step = %2d\n’, x, step);
» test
[base workspace] x = 3.10 and step = 2
[increment call] x = 3.10 and step = 2
[increment call] x = 3.10 and step = 3
[base workspace] x = 5.10 and step = 2 % variable ’step’ from base workspace remained unchanged
To remember …
BewareofCommonPitfalls
Spelling a variable name different ways in different places in a script or function
Forgetting to add the second ‘s’ argument to the input function when character input is desired
Not using the correct conversion character when printing.
Confusing fprintf and disp. Remember that only fprintf
can format.
ProgrammingStyleGuidelines
Use comments to document scripts and functions
Put a newline character at the end of every string printed by
fprintf so that the next output or the prompt appears on the line
below
Suppress the output from all assignment statements in functions
and scripts using semicolon ;
Use the array operators .*, ./, .\, .^ in functions so that
the input arguments can be arrays and not just scalars