Afghanistan
Albania
Algeria
Andorra
Anguilla
Antigua & Barbuda
Argentina
Armenia
Aruba
Australia
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belgium
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire
Bosnia & Herzegovina
Botswana
Brazil
British Indian Ocean Ter
Brunei
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Canada
Canary Islands
Cape Verde
Cayman Islands
Central African Republic
Chad
Channel Islands
Chile
China
Christmas Island
Cocos Island
Colombia
Comoros
Congo
Cook Islands
Costa Rica
Cote D Ivoire
Croatia
Cuba
Curacao
Cyprus
Czech Republic
Denmark
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Ter
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guinea
Guyana
Haiti
Hawaii
Honduras
Hong Kong
Hungary
Iceland
India
Indonesia
Iran
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Japan
Jordan
Kazakhstan
Kenya
Kiribati
Korea North
Korea South
Kuwait
Kyrgyzstan
Laos
Latvia
Lebanon
Lesotho
Liberia
Libya
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mexico
Midway Islands
Moldova
Monaco
Mongolia
Montserrat
Morocco
Mozambique
Myanmar
Nambia
Nauru
Nepal
Netherland Antilles
Netherlands (Holland, Europe)
Nevis
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Norway
Oman
Pakistan
Palau Island
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn Island
Poland
Portugal
Puerto Rico
Qatar
Republic of Montenegro
Reunion
Romania
Russia
Rwanda
Saipan
Samoa
Samoa American
San Marino
Sao Tome & Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Singapore
Slovakia
Slovenia
Solomon Islands
Somalia
South Africa
Spain
Sri Lanka
St Barthelemy
St Eustatius
St Helena
St Kitts-Nevis
St Lucia
St Maarten
St Pierre & Miquelon
St Vincent & Grenadines
Sudan
Suriname
Swaziland
Sweden
Switzerland
Syria
Tahiti
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad & Tobago
Tunisia
Turkey
Turkmenistan
Turks & Caicos Is
Tuvalu
Uganda
Ukraine
United Arab Emirates
United Kingdom
United States of America
Uruguay
Uzbekistan
Vanuatu
Vatican City State
Venezuela
Vietnam
Virgin Islands (Brit)
Virgin Islands (USA)
Wake Island
Wallis & Futana Is
Yemen
Zaire
Zambia
Zimbabwe
Introduction
Computer Setup
Course Example
MathWorks Product Overview
Learning Outcomes
Mathworks at a glance
Learning Outcomes
Optimize performance by choosing appropriate function types
Create robust and user-friendly application interfaces.
Ensure code correctness
Create custom toolboxes
Optimize performance by choosing appropriate data types
Utilizing Development Tools
Assessing code performance.
Debugging code
Finding potential problems in code
Generating reports on multiple files
Outcomes
Use tools like the MALTAB Profiler
Measure code performance
Use integrated MATLAB code analysis and debugging tools
Ensure code provides desired results
Describe the concept of numerical accuracy.
Course Example
satelliteposition() determines satellite location elements or time vector of elements.
User can call readparameters to obtain structure of reuqired parameters from on of the text files
Satellite Tracking
siderealtime() and precession() are private.
satelliteposition() does the math.
satellitefix() determine location relative to fixed location
plotposition() function for visualization.
Debugging Example
satelliteposition() works.
satellitefix() works
readParameters() works.
getElevations() works
getRiseTime() broken.
Folder Overviews
Contents Report
Help Report
TODO/FIXME Report
Code Analyzer Report
Coverage Report
Dependency Report
From folder drop-down -> Reports
MLint
Red: Syntax error
Orange: syntax warning
Green: no detectable errors in the code.
Right-click to flag-off a warning
Can use "Favorites" in MATLAB window to create macros.
%#ok turns off all warnings.
Resolving Dependencies
Dependency Report resolves statically.
local functions: which <function name> in <file name>
Use which <function name>
Won't catch loads or cd's or addpath's from within runtime code.
Debug Mode
Run the code.
Can set conditional breakpoints.
Can "Stop on Errors" from the Breakpoints menu.
Can dbstop command to set breakpoints
Can use dbclear command to clear breakpoints.
Set a breakpoint in a code listing in the editor.
Examining Values
Can also use workspace browser.
Must be in debug mode.
Can mouse-hover over variable names to get values.
Can use Function Call Stack menu to change contexts.
Comparison
Use abs(x-y) < tol
use isequal()
Don't compare doubles with '=='
Performance
Use tic and toc to get elapsed time.
Finding bottlenecks
Generates a bar graph of clock cycles per function.
Use the "Run and Time" button to execute in profiler.
Uses CPU time, not clock cycles.
Use MATLAB profiler
>> profiler('<function>')
Verifying Application Behavior
Using test functions.
Running test scripts
Writing test scripts
Outcomes
Use a test suite to automatically verify application behavior.
Write code that provides tests for desired application behavior.
What is a test?
Formalized statement of behavior
Specific set of circumstances.
Set up circumstances.
Call the application
Define expected behavior
Compare the actual and expected behavior.
A Simple test should:
Writing a test script
Use %% to segment tests in a script.
Should return no response (passed) or an error.
Each test maintains its own workspace when running in a framework.
Must define every variable every time.
store all values in @testcase
use localfunctions() to generate array of test functions in a test script file.
Running a test
Runs every test in the given script file.
Produces an array of test result objects.
>> results = runtests('myTests');
Want benifits of MATLAB test framework.
Can run from the command line.
Note: test scripts can cause their own errors.
Can runtests() on an array of script files.
Testing for Behavior.
Qualification functions are available.
verifyError() etc.
Verify behaviors under conditions, rather than results
Using Test Functions
tests are encapsulated in seperate local functions.
Function script follows a specific template
Input must be used in the validation functions.
First line in master is a call to localfunctions() to find remaining test functions.
First function in the file is the master. Should call all child test cases.
Name of each function should start or end with 'test' (case insensitive).
Single, commonly-named input for all test functions.
>> results = runtests('mainFunctionName');
Passing Commands as Input
Creates an anonymous function.
>> cmd = @() sqrt(9);
Use functional syntax to create a function with inputs.
Adding pre and post test tasks.
Add specific functions:
Add target code paths, etc.
setupOnce()/ teardownOnce()
Can populate the testCase.TestData structure.
Test
(F) If a test fails it proves a bug in the target code.
(T) >> runtests('foo') performs all tests in foo.m
(T) foo.m tests get their own workspace if runtests() is used.
(T) runtests() continues after a failed test.
Creating Robust Applications
Writing flexible function interfaces.
Dealing with error conditions
Validating function inputs
Outcomes
Call query functions to determine properties of variables.
Define default values for function inputs.
Implement a try-catch construct
Use MException objects
Write code to validate assumptions about function inputs.
Provide customized error messages for violations.
Exercise A-4
Debug the functions until they work as expected
Use reports to become familiar with the functions in the Fibonacci folder
Bonus: fund a way to bypass the problem found in step 4.
Is there something that is unnecessarily degradin the performance of the recursive function?
Plot the run times vs. n.
Write a script that calls each function and times how long it takes to run for n = 1,2,...nmax
dbquit will quit progromatically into debug mode.
Increasing Usability
Provide a flexible function interface.
Intercept and recover from error conditons.
Provide meaningful feedback.
Validate all function input.
fix getNextRise()
fix getElevation()
Consider getRiseSet()
Validating Function Inputs
Use size() to validate dimensions.
Use query functions is*() to validate type.
MATLAB function syntax does not prescribe argument type or dimensions.
use validateattributes()
Can allow variable input types/dimensions in checks.
Typically use if/then/else blocks
Custom Warnings/Errors
Errors terminate.
Warnings recover.
MATLAB defaults to full stack dumps on errors.
[msg, id] = lastwarn
Identifier.
Displayed message
Contain 2 components
Hidden from the user.
Allows code to progromatically determine exact warning/error that occured.
Contain at least 2 identifiers separated by a colon.
Should contain info about the source of the warning.
Typically application:component
Utility Toolboxes
Code Generation
Parallel Computing
Other Toolboxes
Geospacial
Biology
Finance
Simulink Layer
Verification, Validation, and Test
Simulation Graphics and Reporting
Real-Time Similation and Testing
Simulink
MATLAB Layer
Math
Statisticts
Application Deployment
Database access and reporting
Optimization
MATLAB
Physics Toolboxes
Control Systems
Signal Processing
Image Processing
Computer Vision
Test and Measurement
Event-Based Modeling
Physical Modeling (SimScape)
@MException
.identifier is the tag.
.message is text
.cause
.stack is the current call stack
A-5
Create a test script to test the functions for a fixed value of n
Fibonacci Numbers II
Verify that all functions produce the same result.
Run the test scrpt and evaluate the results
If the verifications fails determine which functions failed.
Investigate cause of failure.
Bonus: repeat steps 1 and 2 using a test function.
Try-Catch
Should either recover or halt execution.
Can examine exceptions programatically.
catch (@MException)
Creates a stanza
throwAsCaller issues from the current line of code in calling function.
throw re-issues from the current line of code.
rethrow re-issues the error from the offending line of code.
Setting default function input values
Parameters are assigned in order. Can skip with [ ].
Use an if nargin < n to define n'th default.
use nargin to determine how many arguments the function recieved.
In case the caller got lazy.
Can switch behaviors depending on nargin.
Test for this with an isempty() on the n'th argument.
Parsing Property-Value lists
Use switch propertyName to deal values
Use vaidatestring() to check names
use @inputParser
Test
Can't use validate*() for general use. Must be in a test framework.
Time of error fail is not provided by @MException.
Users can optionally disable warnings.
Structuring Code
Local functions
Private functions
Precedence rules
Anonymous functions
Function handles
Nested functions
Comparison of function types.
Outcomes
Select approriate type of MATLAB function based on requirements for function visibility and workspace access.
Create and call an anonymous function to change the interface to an existing function.
Determine which function a program will call when multiple possibilities exist.
Private Functions
Separate .m file
Separate workspace.
Sees/calls in parent and /private folders.
For project-specific functionality.
Cannot be added to the MATLAB search path
in a folder called /private
Can be in any folder.
Local Functions
Can be used to segment workspace variables by algorithm use.
Hides function utility.
Can only see/call w/i same .m file.
Has a separate workspace.
In a shared .m file
Only the function matching the file name can be called from outside the .m file.
'end' is optional between local functions. Must be consistent w/i a file.
Nested Functions
Parent function can access child workspace.
Used to share application data.
Can see/call parent function, siblings, and all lower-level functions.
Shares workspace with parent function.
In same .m file w/i another function definition.
Must use 'end'.
Cannot span scope of double nests.
Used for parsing functions.
Used for sub-algorythms.
Used for GUI callback functions
Memory efficient. Doesn't pass by value.
Function Handles
Data necessary to execute the referenced function.
Name of the referenced function (if any)
Type of the referenced function
Stores
functions(@) returns information
func2str(@)/str2func(@)
Location of the referenced function
Pass functions as input to another function
Used for
Keeping function calls flexible/dynamic
Extending the visibility of a function
Changing the interface of a function
Anonymous Functions
No static code.
Scoped where defined.
Referenced via function handle variable.
Used to change function interfaces.
Must be a one-liner.
funvar = @(<args>) <code>
may include values from definition scope.
Changing interfaces
Use arguments from the definition workspace.
Create wrapper functions.
Computationally efficient (saves parameter recalculation).
Can reduce the signature of underlying function.
Function Prescidence
Class method
Function from an imported package.
Variable in the local workspace.
Function on the MATLAB path
Function in current folder.
Class constructor in an @folder
File Precidence
Built-in files (.bi extension)
MATLAB code files (.m files)
Obsfucated MATLAB code files (.p's)
Simulink models (.slx or .mdl's)
MATLAB executable (MEX) files (.mex*'s)
A-6
Modify the code.
Open moonphase.m
Add default values for last 3 arguments.
Ensure user passes in 3-6 arguments
Consider using a switch/case statement
use @inputParser?
Test
Private vs. local functions.
Cannot be called from the command-line
Nested functions
Share variables within the same file.
@ to an anonymous function is best suited to
Differ by scope visibility.
Have a higher priority than local and private functions.
Passing optional function arguments by sharing variables with the calling function.
Structuring Data
Extracting and converting
Container types for heterogenous data
Available Data types
Custom data types
Outcomes
Convert and concatenate data stored in cell arrays, structures and structure arrays
Consider memory usage
Select the most appropriate data type for an application
Consider data extraction
Extract and manipulate subsets of data from various data set organizations.
Course example
Pass a list of visible satellites.
Generating a report
Items in list will be different sizes.
Elements are heterogeneous.
Considerations
Careful use of I/O
Speed.
Needs processing.
Data
Using built-in types uses pre-compiled code.
Memory usage
Preprocessed for conditon checking.
Use pre-allocation
Use vectorization
Overhead for structured containers.
Avoid temporary copies.
Reduce data overhead.
MATLAB data types
calendarDuration
duration
datetime
Structure
Table
char
Time
Heterogeneous
Cell
Text
Categorical
logical
function handle
numeric
double
single
uint(8,16,32,64)
int(8,16,32,64)
Tables
Each column must have a unique name.
Require all elements have the same component types.
Require all elements the same size.
Each column has the same number of rows.
Columns are "variables".
Can concatenate using [ ]
Can merge with join(), innerjoin(), and outerjoin().
Can use regular array indexing with either numeric or named references.
Can extract whole variables using dot referencing.
Must be able to concatenate to the same type.
Can't perform operations on type table.
Memory overhead is O(1)
cell arrays
Can be used to store lists of optional arguments varargin's.
Often used to store lists of char
empty cells are allowed.
Use curly braces to concatenate elements into a cell array.
Can concatenate using [ ]
Can contain data of different types and/or sizes.
Can use standard array indexing.
Memory overhead is O(n)
Indexing to multiple cells
{ } breaks cell arrays into a comma-separated list
cat() also helps with cell extraction
Must concatenate [results] as it runs.
Indexing runs before output.
indexing into multiple cells returns a comma-separated list of the contents.
"Curly for content"
Structure arrays
Uses named fields like a table.
Holds dissimilar content like a cell array.
Can slice through a structure array by record number or by field.
Fields are created on assignment.
Field contents do not have to be the same length or type.
Dot-referenced using fields.
All structures in a structure array must have the same fields.
Converting cells and structures
Need to tell cell2struct what the field names are.
Must flatten deep cell arrays first.
Converting data types
Not all conversions exist.
Comprehensive set of conversion functions exist.
Only conversions that make sense exist.
Some conversions are just typecasts like char()
Might need to pad strings to even if converting to a char array.
Custom data types
uses properties for fields.
use classdef <blah>
See object-oriented programming course.
Must define all behaviors in methods.
Other data types
@Map, @Line, etc
These are all objects.
A-16
Units class
Custom data types
Results should be in units
ensure labels are consistent
Overload function for adding
Open units.m in the MATLAB editor
Add a display()
Managing Data Efficiently
Vectorizatoin
Preallocation
Memory and efficency
Memory management
Outcomes
Use vectorization techniques to improve code performance.
Write code for preallocating various types of arrays
Explain memory usage when passing arrays to functions.
Memory Anatomy
sys.PhysicalMemory
[user, sys] = memory
user.maxPossibleArrayBytes
No default on array size beyond system limitations
Memory usage
double take 8 bytes
Arrays have no extra overhead.
Logical is stored as an unsigned 8 bit integer
120 bytes overhead per cell in a cell array
Tables are much more memory efficient.
MATLAB intrinsic types have overhead.
Memory efficiency
Data Type memory usages
System limitations
Computational Efficency
Use intrinsic MATLAB types to use pre-compiled code.
Leave the back-end clean.
Do the messy stuff on the front end.
Preallocation
Want arrays stored in contiguious memory
MATLAB arrays are arrays of pointers.
Arrays must be copied if you expand them.
Scales with O(N^2)
Use zeros() to pre-allocate continuous memory
Cell array pre-allocation only creates the pointer array.
Must still pre-allocate the cell content arrays
Preallocate structure arrays by defining the last structure element in the array.
Vectorization
Does a single function call instead of multiple interprets
Runs c-code instead
Use vectorized operations instead of for-loops
Use "extraction, conversion, and concatenation" techniques
Use dimension arguments
Use logical indexing.
Applying scalar functions to an array
Use functional programming
cellfun( )
structfun( )
arrayfun( )
Vectorization wrt Memory
Consider the bsxfun(@,x,[blah blah2 blah3])
All operators have an equivalent functional form.
sum(X,2) (second attribute for dimension ordering)
Arrays are stored column-wise (FORTRAN)
Do operations down the primary dimension per storage in memory
bsxfun( ) is now adopted as base MATLAB behavior.
Copy-on-Write
If values are modified THEN it passes by value and creates the copy
MATLAB passes by reference AT FIRST
Look at the memory() function
In-Place optimization
Use same variables across call and return of functions
Reuse same variable across function input and output
Reuse same variables across assignments
More useful for larger data sets
Test
The most memory-efficient way to sum the rows of x = rand(2000)
It is important to preallocate before an array size grows during a for-loop
len = 10 3 2
len = cellfun(@length,C)
out = sum(x,2)
C = {1:10, [2;4;6], {1,2}}
Creating a Toolbox
Packaging the toolbox
Creating Documentation
Distributing the toolbox
Outcomes
Create documentation for a custom toolbox
Package code and documentation as a custom toolbox
Course example
Satellite Tracking Toolbox
Package it for shiping as a toolbox
Why?
Easy user install
Resolves path requirements
Can include custom documentation
Users can manage toolboxes in MATLAB including updates and uninstalls.
Packing a toolbox creates a single installation file.
Organizing Custom Documentation
Create a documentatin folder within your toolbox folder.
Individual documentation pages, in the form of .html files in the documentation folder.
An XML filed called helptoc.xml in the documentation folder
An XML file called info.xml located within the toolbox folder.
Can be in subfolders as long as they are on the MATLAB path when the packager is run.
Typically code is in a seperate folder than the documentation.
Other folders may contain examples, data files, or other supporting files.
Modify tag content of template
Creating Documentation Pages
Is a seperate file
Can use the publishing feature of MATLAB
Can use a web-page authoring tool
Can write HTML files directly
use publish()
Fill out template html
Providing meta information
Nothing but the help file info
Packaging the toolbox
Specify
Top-level folder of your toolbox files
The name of yur toolbox
AN icon for the toolbox
Information such as author, version number, and a description
Distributing the Toolbox
A-18
Write a function called pio4() that uses a for-loop to compute the sequence
pi/4 ~ (-1^n)/(2n + 1)
Compute pi/4
Write a script called pio4_comp.m that measures times spent by these functions.
Write a function called pio4_vec() that uses vectorization
Write a function called pio4_pa() that uses preallocation
Project folder organization
class definiton.m's
/examples
/help
/private
"Documentation folder" can be called anything?