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
Utility Toolboxes
Code Generation
Parallel Computing
Other Toolboxes
Geospacial
Biology
Finance
Physical Modeling (SimScape)
Simulink Layer
Verification, Validation, and Test
Simulation Graphics and Reporting
Real-Time Similation and Testing
Simulink
Physics Toolboxes
Control Systems
Signal Processing
Image Processing
Computer Vision
Test and Measurement
Event-Based Modeling
MATLAB Layer
Math
Statisticts
Application Deployment
Database access and reporting
Optimization
MATLAB
Introduction
Course Example
Learning Outcomes
Why OOP?
Event listeners
Custom containers
pass by value and reference
Class definition of properties, methods and events
Enforce type and value for storage
Restrict data access
Structure and its field values can be changed by the user
Structure does not impose restrictions on values.
Each function would need to check the consistency of the structure
Creating Custom Data Types
Writing a class definition
Documentation custom classes
Creating and using an object
Packaging multiple code files
Outcomes
Set property values at creation time using the constructor
Avoid unintented changes using porperty validation
Define a new data type with a fixed set of properties
Prevent naming conflicts using packages
Add functionality to a data type by writing methods
Course Example
"temperature" class
Try creating a temperature
Uses validateParameters()
Plot() labels y axis with labels, colors by value, etc.
Has an add()
Store temperature data
Combine measured values
Handle masurement units
Store a descriptive text
Convert units
Plot temperature data
Avoiding name conflicts
Use package directory.
Can "import" package directory by name.
Special folders that begin with '+'
Contains
Functions
Classes
Other packages
Defines a scope or "namespace"
Names need to be unique only within a package directory.
Organizes classes and functions for reuse.
Parent folder must be on MATLAB path
Access contents with package.content
Can list package contents with what('pkgName')
Defining a New Data Type
Gives template
New Class
New
From the home-tab
Class definitions end with 'end'
classdef starts a class definition
Class definition file
Instances created by creating variables of the new class type
Is a mix of both the structure and related functions.
General description of class should follow classdef line in comments.
Create a class definition file from new for the temperature class
Storing data in properties
Cannot add properties to an instance of a class outside its definition.
Can add comments above the property name to document its purpose.
Assign values with dot notation
Properties block contain data
Declare properties in block
No constraints are defined.
Create an instance of the temperature class
Methods
All methods require the current object, commonly named obj, as the first input argument.
Are defined in methods blocks w/i the class definition file.
Have access to all properties and other methods regardless of attributes
Methods are class-attached functions
Explicitly define how user code can interact with an object of a class
Except static methods
Can call methods in two ways
Functional: methodName(objectName)
Object-Oriented notation: objectName.methodName()
Convert plot and combine into class methods of @temperature
Watch for class on return value.
cntrl-i for auto-indent!
Make comments on end line, so they show when collapsed.
Course Outcomes
Reduce code repitition by applying inheritance and aggregation
Design a class for robustness, usability, maintainability, and efficiency.
Creating variables of custom types (classes)
Extend built-in MATLAB capabilities by prototyping a custom data type (class)
Organize a collection of user-defined code files b employing package folders.
Identify the use cases for pass by value and pass by reference
Verify the required behavior of a user-defined class using the MATLAB unit-testing framework
Enable dynamic behavior and object synchronization using events and listeners
Can restrict values in parameter definitions.
Add restrictions and default values to temperature class definition file
= default value assignment
List of validation functions as a {comma-separated list} of function names with (arguments)
Specify data type after size restriction
Specify the size of each dimension in a (comma-separated list)
MATLAB will attempt to cast types on assignment.
Additional arguments must be literal values (cannot reference variables)
mustBe*
Constructor
Can only define one constructor per class.
Can implement consistency checks inside a constructor method
Name must match the class name.
Must be public
Is a method of the class
Can use flexible function interfaces (nargin) to provide several variants.
Add complete documentation after the definition line of the constructor.
returns an instance of the class (traditionally called 'obj')
Create a temperature object with initial data.
Default constructor
Takes no inputs
returns an instance
All parameters are empty array.
edit('generateCh2EndTests')
run(generateCh2EndTests)
Test
Should provide multiple implementations for user inputs.
All inputs should be validated before assigning them to properties
Initialized object is the output
myPkg.myFct()
Call myFct in the package myPkg
When writing a constructor
Designing a MATLAB class
Customizing standard MATLAB operators
Defining safe interactions
Establishing intuitive coding
Prohibiting data inconsistencies
Outcomes
State the precedence rules for function and operator calls.
Customize standard operators for user-written classes.
Separate a class's interface from its implementation using property and method attributes
Ensure data consistency using data access methods
Prevent inconsistency
Course Example
Customize standard operators
How can you combine two temperature objects with differing units?
How can you allow for direct access to the Units property whie keeping MeasuredValue consistent?
Need to protect data and avoid inconsistencies.
Want to write simple, intuitive and powerful interface.
Using property and method attributes
Write data access methods
Create some temperature data
Combine them.
Property attributes
Balance safety vs. usability
Can allow or prohibit interaction with attributes
Get/SetAccess
Dependent: virtual
Constant: immutable, static
Write attributes after properties block header ( in)
protected
private
public
immutable
Common to omit '= true'
Can add any number of attributes to a property block
Writing data access methods
New Data
Existing Object
Updated object
Warning | error
function obj = set.PropName ( obj, value)
function s = get.PropName(obj)
set method w/ checks
Not user-accessable
Performs consistency checks on sets
Public/Private Property Pairs
Real value is stored in a private value.
There for user to interact with.
Never going to store value
Use dependant property pairs
Introduce DisplayUnits
Make Units dependant on DisplayUnits
Add ValueInKelvin
Method attributes
Abstract
Access
Hidden
Sealed
Static
Set properties to a methods block
true | false
public | protected | private
MATLAB operators
All operators have equivalent functions
Rely on the MATLAB code as much as possible (wrap it)
Overload functions by group, not individually.
Don't derive operators from one another.
See table for operator <-> function
Write a helper function
Pass in a function handle
Expose underlying numerical values
Call the function handle
Can't overload the assignment operator
Precedence rules
Local functions within the current file
Nested functions within the current function
Imported package functions
Variables in current workspace
Object methods
Private functions
Class constructors
Functions in the current folder
Functions elsewhere on the path, in order of appearance
User-defined classes run before built-in classes.
Can use InferiorClasses attribute
If no precedence then left-most object runs first
Create some data
Compare both temperatures
Compare both measured values
Compare temperatures with doubles
Shows up in the automated help
Creating custom validation functions
Return nothing or throw error
call mustBeMember( input, {set of allowed values})
take in one input argument
Defined as local functions to classdef file context
Test
Define public property to Dependent
Set | Write Access
Determines mutability from the comand line
Functional for '*' and '&'
Define a public|private pair you must
Class Hierarchies
Testing class hearchies effectively.
Extending and specializing existing classes via inheritance
Making code reusablevia abstraction
Avoiding code duplication by introducing superclasses
Think about use cases and visibility in advance of the design
Use UML diagrams
Outcomes
Specialize object behavior via subclass implementations.
Derive a new class from an existing one using inheritance.
Define a standardized interface using abstract properties, methods, and classes.
Replace duplicate code from multiple classes by one common superclass.
Example
All have common methods
Generic measurements
Derive mass & temperature
Refactor tests per new heiarchy.
Compare class definition files using visdiff(1,2)
Specialize each subclass.
Avoid cut/paste duplication by using a superclass
Creating a superclass via Abstraction
Cannot be instantiated
Abstract class
Declared in abstract classes
Implemented in subclass
Can be instantiated
Concrete class
Abstract members
Contains no abstract members
Interface
Requires subordinate classes to support parameters and methods
classdef (Attributes) classname
Inheriting from a Superclass
Private -> Protected
classdef child < superclass
Can overload superclass members
Can add new members
Not public
Can be inherited
Sharing Common Properties
(Abstract, Private) -> (Abstract, Protected)
Must support abstract properties
Move set/get methods to the superclass
(Abstract, Constant) -> constant in subclass
Sharing Common Methods
All method blocks must have the same attributes
Child classes Must support abstract methods of the superclass
For construcor: obj@superclass()
Calling Superclass Methods
Use methodname@superclass()
Good for wrapping superclass behavior.
Testing Class Hierarchies
Consider mocking framework
Test code where it is written.
B-19
Implement calculateArrivalDelays
Pass a set of key-value pairs
Implements a Python Dictionary.
containers.map
Look into rmmissing() and ismissing()
Implement calculateDepartureDelays
Open ch2solutions.flight
Output average arrival delays
Calculate average departure delays
look into splitapply() function
zoomit
Test
Facilitating multiple References
Pass-by-Reference
Identifying the use cases
Refrencing a data object from multiple viewers
Creating versatile view class and objects
Creating indepenent copies
Pass-by-value
Outcomes
Create copies of objects explicitly
Implement a class whose instances exhibit reference behavior
Write context-sensitive applications by exploiting polymorphism
Embed on e class into another using aggregation
Example
Should be able to display any concrete subclass of measurement
Only change when source object changes.
Two viewers should be able to display the same object, not identical copies of it.
Measurement viewer
Update when source data object changes
Should display measurment it is given.
Aggregation
Define base class first.
Strong inter-class relationship.
Compositon
Copy files to work directory
Aggregation
"has a" relationship
Contains or is composed of other classes.
Then include copies in the containing class.
Writing context-sensitive code
"Factory" Pattern?
Call common methods.
Exploit polymorphism.
Write a measurementViewer version that is sublcass agnostic.
Referencing objects from many viewers
Pass by value by default.
< handle
Now passes by reference.
Consequences of Reference Behavior
< handle
Has a delete() method
Destroy data behind the reference.
clearing retains data.
Use copy() to duplicate target data
Set methods no longer return obj.
Data can be mulit-referenced.
deleting retains handles.
Overload delete() to write a destructor.
matlab.mixin
Copying and Deleting Handles
= adds a new reference
copy() makes a deep copy.
clear removes a handle
delete removes deep object data.
Can accidentally screw up other references.
Choosing a Handle | Value class
Handle class
Value Class
I am the thing
Machine learning
Changing from anywhere should change everywhere.
I know the thing is over there.
Aspect
Constructor output
Data object itself.
Reference to the data object.
Result of assignment
Copy of the data object
New reference to the data object.
Modified function inputs
Must be returned as outputs.
Automatically affect the caller workspace.
Typical Use
Data Structures
Unique objects (graphics)
Test
Is a sublcass of handle
Provides a method for creating independent copies of objects
Is an abstract class
Define the classes as properties of the container class
To aggregate several classes into a container class
When you delete the last reference MATLAB deletes the data.
matlab.mixin.Copyable
Writing Tests
Aggregating, running, and logging test cases.
Authoring lean and clean test classes
Writing tests to verify method behavior against requirements
Testing custom classes with custom test classes
Outcomes
Analyze and log the test results.
Combine multiple test cases into test suites and run them.
Refactor test code to make it concise and efficient.
Implement test methods folowing the SEAT structure
WRite test classes that inherit from matlab.unittest.TestCase
Motivation
Check code coverage
REpeated test runs whenever codebase is changed.
Automate testing against all requirements.
Structure test code to avoid duplication
Employ verification test methods
Refactor existing test functions
Parameterization
Aggregation
Unit Testing Framework
Test writing is a means of formalizing requirments.
Unit can scale from functions to whole classes.
TDD Test Driven Development
Overview
The unittest package
.plugins
.@TestRunner
.@TestSuite
.@TestCase
.qualifications
.diagnostics
.constraints
Deriving custom test cases
Derive from matlab.unittest.TestCase
methods block for nameOfTest() functions has attribute "Test".
Passing testcase into methods is the same as passing obj.
Selecting the test type
fatalassert
verify
What do you want to assert?
assert
Table of functions follow.
Then pick a condition
assume
Implementing Test methods
Use assume*() to check setup.
Verify debris from previous tests with verify*()
See table for behavior of various function families.
Use assert*() to enforce setup.
Can provide tolerances, etc as optional inputs.
Do fatalAssert on constructor.
Refactoring Test Cases
Test Clas Teardown
Test MethodTeardown
Test
TestMethodSetup
TestClassSetup
@TestCase
Parameterizing Unit Tests
Will execute selected combinatoric of given parameters.
Set ParameterCombination attribute of test method block.
Pass parameters to test functions
@TestCase Parameter block
Parameters must be a cell array or a structure.
Use structures to get named results.
Use function handles or dynamic indexing in parameters to test multiple fields with the same data
Testing for Errors
Function handle to execution phase of your test (piece of code that is supposed to fail.)
An instance of @TestCase
use assertError to avoid having to try-catch code.
Use MException.last to determine last error if unknown.
Expected @MException identifier.
Needs:
Test Suites
.fromName()
res = run(suite)
.fromClass()
.fromPackage()
Use methods to state test source.
.fromMethod()
.fromFolder()
Check extra parameters in docs
any(res.Failed)
Logging test and Coverage Results
Can add plugins to default test runner.
Code coverage plug-ins.
Identify SOT to plug-in.
Call .addPlugin on test runner.
res = run(runner,suite)
Failure diagnostic plug-ins.
Creat a test runner.
Open code in profiler for test coverage report in detail.
Test
inputs to assertEqual()
True for a failed verificatoin?
Valid method attributes of .TestCase
4 phases of a test
Synchronizing Objects
Trigger calls based on custom events
Events
Automatically react to property changes
Listeners
Callbacks
Only work for handle classes.
Outcomes
Special situations during the processing of other objects
Chages in parameters in other objects
Create objects that react to
Course Example
Leverage pre-defined property events and listeners.
Enable automatic synchronization
Synchronizing 2 or more objects throughout their lifecycle.
Updating Viewers
Hook up events and callbacks through listeners.
Write callback functions.
Distributes responsibility among objects
Events, Listeners, Callbacks
Events are broadcast.
Events are notifications.
Listeners execute callback functions when events occurs.
Events are triggered in response to some action or circumstance.
Using pre-defined Property Events
For every handle class property
GetObservable
Attributes
PreSet
PostSet
Set to true then events are triggered on read | write access.
SetObservable
PostGet After gets are serviced
PreGet before gets are serviced.
Can list allowed listener classes.
Defining Listeners
propName - property name to listen to
eventName to listen to
Use listenObj = listener(obj, 'propName', 'eventName', @callbackFct)
@functionName
@obj.methodName
Obj -handle to event source object
@callbackFct callback function to execute
@className.methodName
Set attributes to listener parameter to immutable, private
Can be a cell array
Implementing Callbacks
Source meta.property that triggered the event.
EventName
AffectedObject
instance of event.PropertyEvent
@handle object of event source.
Can do whatever in the callback function.
Must accept 2 auto-generated inputs.
if using a class method then must align the method interface with the necessary interface for a callback.
Define an appropriate function handle.
function callback(src, event)
src is going to be the actual atribute we're listening to.
@(src,evt) update(obj,src,evt)
@(src,evt) update(obj)
Querying Class Information
Each attribute corresponds to a property in the metaclass
Contains attributes of that block
Each block has an associated metaclass
meta.class, meta.event, meta.method, meta.package, meta.property
is in the .meta package
And visa versa.
Metaclass objects
?className returns meta.class for the named class
meta.class.fromName('className')
metaclass(obj)
findprop() retrieves metadata
metaInfo = ?measurement
Defining Custom Events
notify (obj,'EventName')
Call its notify function:
Name your events
Create an events block
Can add a line of comments before event name.
Check block visibility
Listening to Custom Events
Standard @callback notes apply (same two arguments)
Assign to obj.custlist = listener(obj.Measurements, <eventname>,... @callback)
Add a new listener
Source object who's class defines the event.
Source
EventName
Test
callbackFunction(source,event)
Pre|Post && Get | Set
Pre-defined property event types:
Pre-defined interface of an event callback function?
Static Methods
Not dependent on an instance of the class
Does not take the object as a first parameter
All containing methods block have to have the same attributes.
B-27
Split flight analyzer and flight classes.
TDD Benifits
Early identification of problems
Motivates modularization
Facilitation of subsequent code changes
Clearer documentation
5 Rules for TDD tests
Self-Validating
Repeatable (independant from environment)
Independant from each other
Run fast
Timely (written before code)
SEAT
Assert (pass|fail?)
Whatever you need to exhibit and observe behavior.
Setup
Teardown (undo setup)
Execute (interact with the SUT)
TestResults.table()
Testing Abstract class
Make a mockup of child classes.
Keep mockups as simple as possible.
Look into the mocking framework
B-36
Old-style Syntax
Paradigm
Outcomes
Convert a non-trivial object
Apply logic to paradigm differences to extract syntax and behavior
Understand paradgm differences
Paradigm
class definitions are fixed within a session.
Objects are structs.
Data
Defining classes is done in the file system.
Methods
Inheritance
Documentation
Field immutability
Can change the class definition by first clearing it from the workspace.
Attempting to modify an object's fields generates an error.
The number and order of fields is immutable.
Data contained is not enforced, only the fields themselves are.
File system
All class artifacts must be stored within folders named after the class.
Methods are set to private by storing them in a /private sub-folder to the class folder.
Multiple @folders may exist for a given class name.
Function calling precidence is from inside-out, starting in /private, then @folder.
Parent folder to class folders must be on the MATLAB path.
Class folders begin with @
Constructors are files within class folders with the same name as the class.
Constructors
Only a constructor function can create a new instance object of the class.
Have the same name as the class.
Methods/Functions
Are stored in the class folder.
Exist in their own files?
Are called by name.
functions that take a handle to an object as the first argument.
All user interaction with a class must occur within a member function.
Some function calls can be hidden within accessor functions.
Members/Data
Class members are defined as fields in an input struct to the class() function.
All data is private. It can only be modified by a class's member functions.
Required Method Interfaces.
Required to be an object
Constructors
Optional intrinsic overloads
Are called first because of function precidence.
Have the same names as built-in functions
builtin() can be used to evoke the intrinsic function.
Arithmatic operators are available via their function names.
Display()
obj may be an array of objects.
Takes one argument: obj.
Intrinsically called when statements end without colons.
Must respect the 'FormatSpacing' of the root object.
format loose
format compact
Accessor Methods
Provided to shorten some calls.
Because using a method function to perform every action is very limiting.
subsref() & subsasgn()
Invoked every time an access statement is done.
subsref()
subsref(A,S)
Typically nargout = 1.
Requires nargout >1 for cell or struture indexing with arrays.
subsasgn()
Returns one output.
Updated object once assignment is completed.
May require an array of data
Most calls will only have 1 value to assign.
Taks N+2 arguments
subsasgn(A,S,varargin)
varargin - values to be assigned.
A is the object to be indexed | assigned
S is the index structure.
Index Structure
Types in the '()' sub do not have to be numbers. Characters etc. are legal.
N is the number of nested indicies structures used.
1xN structure array
.subs
Cell array of index values.
string of either '()', '{}', or '.'
.type
Colon syntax arrays are expanded before calling subsref.
'{}' is exactly the same as '()' indexing, except for type.
'.'-typed subs will always be a string.
numel()
called before subsref() or subsasgn.
Determines how many elements are present.
Determines required number of arguments for '.' indexing.
Default numel() works fine for most cases.
Takes one argument: object to get number of elements.
Conversion constructors
Will invoke target class constructor if source conversion constructor is not found.
Overloads constructor of the target class.
Should be placed in the @ folder of the source type.
Member functions with the name of the target type.
Better to provide a conversion constructor than bloat the target class with code to deal with targeted casts.
Will auto-generate call implicitly on casts.
Inheritance
Placed in the new object in fields of their type name.
Pass in already-constructed objects
Additional class() arguments.
Provided by Matlab
Inherited fields are still private.
Agregates incoming objects in name-value pairs into a master structure.
Method scope is as defined.
Function precidence is inside-out: child first, then parent.
Documentation
HTML Demo Pages
HTML Doc Pages
Comment Headers
Comment Headers
Parses "see also"
H1 is the first line. 1-line summary.
help displays them.
First block of comments in an m-file.
Class name/function i.e. FRESPID_OBJ/SAVE
Can go to any member function, then to general functions.
No required structure.
Suffice for simple documentation.
HTML doc pages
need an info.xml and helptoc.xml.
Requires more inputs to MATLAB.
Provides the tree for the help browser.
helptoc.xml
Sidebar access only. Can't doc yet.
Search database must be created from the HTML documents.
builddocsearchdb()
doc querries search databases for function name.html and files marked 'reference'.
'reference' is a meta tag in the <head> section of the HTML document.
<meta name = "chunktype" content="refpage">
info.xml
Specifies where help files are located.
specifies toolbox title
Located on the MATLAB path
$toolbox
$matlabroot
help location can be relative to info.xml or absolute.
expand to the MATLAB root
Expands to MATLAB toolbox directory
HTML demo pages
there is a folder called 'html' in the directory that the .m or .p file resides
Help command will make a link to an html document as a demo of that file if
Within that directory is an html file with the same name.