Adaptive Algorithms andParallel Computing
Object-Oriented Programming in MATLAB (Primer)
Academic year 2014-2015
Simone Scardapane
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
What is OOP?
Procedural programming
• Procedural programming languages (e.g. C) focus on definingprocedures that implement the core logic of your problem.
• This is decoupled from identifying suitable data structures.• Object-oriented programming (OOP) is a programming
paradigm where the focus is on representing the domain of yourproblem using objects.
• An object encapsulates an internal state, and exposes somemethods through an interface. In this sense, it combineshandling data and operations.
• Note: a class is the source code, from which multiple objects areinstantiated.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
What is OOP?
Benefits of OOP
ModularityOOP forces the developer to design modular software.
Data encapsulationAn object can hide part of its information at run-time.
Logic encapsulationIt is not necessary to understand the internal logic of an objectbefore using it.
MaintainabilityOOP code is easier to maintain/document/debug.
ExtensibilityFeatures such as inheritance makes OOP code easier to extend.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
What is OOP?
OOP in MATLAB
• Full support for OOP (with a completely rewritten syntax) wasintroduced in MATLAB R2008a.
• Since then, many basic functionalities have been re-introduced tobe compatible with an OOP standard.
• As an example, the graphic engine from MATLAB R2014b isclass-based (so-called HG2).
• MATLAB R2015a has introduced additional functionalities interm of editing capabilities.
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Syntax: defining a basic class
Defining a class
A class is instantiated with the classdef keyword:
c l a s s d e f Rectangle
p r o p e r t i e s% P r o p e r t i e s go here
end
methods% Methods go here
end
end
The source code must go inside a file with the same name (e.g. ‘Rect-angle.m’).
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Syntax: defining a basic class
Defining a property
The internal state of the class is saved as properties of the class:
p r o p e r t i e swidth ; % The width of the r e c t a n g l eheight ; % The height of the r e c t a n g l e
end
MATLAB is weakly typed, meaning there is no need of defining the typeof each property. A class without methods is equivalent to a struct.
>> r = Rectangler =
Rectangle with properties:width: []height: []
>> r.width = 5r =Rectangle with properties:width: 5height: []
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Syntax: defining a basic class
Defining a constructorAn object is created by invoking a special method known as construc-tor. Let us define a custom constructor for our class:
methodsfunct ion obj = Rectangle (w , h )
obj .width = w ;obj .height = h ;
endend
The constructor has a very specific syntax. By default, MATLAB gen-erates a default constructor with no input arguments. Since each classcan only have a single constructor, our definition overrides the MAT-LAB one:
>> r = Rectangle(3, 2)r =
Rectangle with properties:width: 3height: 2
>> r = RectangleError using Rectangle (line 10)Not enough input arguments.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Syntax: defining a basic class
Defining a methodThe third essential element of a class definition is a set of methods:
methods
% Constructor goes here
funct ion p = get_perimeter (obj )p = 2 * (obj .width + obj .height ) ;
end
funct ion obj = scale (obj , n )obj .width = n*obj .width ;obj .height = n*obj .height ;
endend
>> r = Rectangle(5, 3);>> per = r.get_perimeter()per =
16
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Static and private elements
Defining a static methodA static method is associated to a class, but not to any specific instanceof that class. Here is an example of a static method:
c l a s s d e f Rectangle% Previous code goes here
methods (Static )func t ion s = get_description ( )
s = ' Class f o r represent ing r e c t a n g l e s ' ;end
end
Note that a static method does not need an instance of the class as ar-gument. In this way, you can call a static method without first declar-ing an object:
>> Rectangle.get_description()ans =
’Class for representing rectangles’
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Static and private elements
Defining a constant property
A class in MATLAB can have a constant property (or more than one),i.e. a property whose value is never modified after the first assign-ment:
c l a s s d e f Circlep r o p e r t i e s (Constant )
pi = 3 . 1 4 ;end% Other d e f i n i t i o n s
end
>> Circle.pians =
3.1400
>> r.pi = 2You cannot set the read-only property ’pi’ of Rectangle.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Static and private elements
Defining a private propertyFinally, a MATLAB class can have one or more private properties, i.e.properties that should not be visible (nor modifiable) from the outside:
c l a s s d e f Rectanglep r o p e r t i e s (Access = private )
width ;height ;
end% Other d e f i n i t i o n s go here
end
>> r = Rectangle(3,2)
r =Rectangle with no properties.
You can also have private methods (using an equivalent syntax). Simi-larly, you can have properties that are visible but not modifiable: [Spec-ifying Property Attributes].
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Class documentation
Writing the documentationWhen documenting your class, you should be careful in respectingMATLAB conventions:
c l a s s d e f Rectangle% Rectangle − Class f o r def in ing r e c t a n g l e s% This c l a s s can be used to def ine o b j e c t s represent ing r e c t a n g l e s .% I n i t i a l i z e the c l a s s as :% r = Rectangle ( 3 , 2 ) ;% Then , [ . . . ] .% See a l s o : UINT32
p r o p e r t i e swidth ; % Width of the r e c t a n g l eheight ; % Height of the r e c t a n g l e
end
methodsfunct ion p = get_perimeter (obj )
% Compute the perimeter of the r e c t a n g l ep = 2 * (obj .width + obj .height ) ;
endend
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Class documentation
Accessing the documentation
>> help RectangleRectangle - Class for defining rectanglesThis class can be used to define objects representing rectangles.Initialize the class as:r = Rectangle(3, 2);
Then, [...].See also: uint32
>> help Rectangle.widthwidth - Width of the rectangle
>> help Rectangle.get_perimeterCompute the perimeter of the rectangle
>> % See for yourselfdoc Rectangle
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Handle and Value classes
Difference between handle and value classes
• All the classes that we defined up to now are value classes. Whenyou pass a value class’ object to a function, a copy is created(similarly when you assign to another variable).
• You can create handle classes that work in the opposite way.Passing an object of an handle class to a function passes areference to the object itself.
• Value classes are useful when the semantics of your objects issimilar to numerical classes or data structures. Similarly, handleclasses are useful when there is often the need of sharing objects.
• This is especially confusing because the resulting syntax is mixedwith respect to other common programming languages (e.g. Javaor C++).
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Handle and Value classes
Defining an handle classAn handle class should derive from the basic handle class (more on thissyntax later on):
c l a s s d e f Rectangle < handle
p r o p e r t i e swidth ; % Width of the r e c t a n g l eheight ; % Height of the r e c t a n g l e
end
methodsfunct ion obj = Rectangle (w , h )
obj .width = w ;obj .height = h ;
end
funct ion scale (obj , n )obj .width = n*obj .width ;obj .height = n*obj .height ;
end
endend
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Handle and Value classes
Using an handle class
>> r = Rectangle(3, 2);>> r2 = r;>> r2.scale(2)>> r2
r2 =
Rectangle with properties:
width: 6height: 4
>> r
r =
Rectangle with properties:
width: 6height: 4
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Events and notifications
What is an event?
• A very interesting aspect of handle classes is their ability ofdefining events.
• Roughly, an event is a specific message which is triggered atcertain points in the code. This is known as notification.
• It is possible to associate one (or more) listeners (also known ascallbacks) to a specific notification.
• In this way, you can define a dynamic behavior that is executedat runtime depending on how the class is used.
• As an example, we will show how to keep track of how manytimes a specific function is called.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Events and notifications
Defining an event (1/3)
First of all, you must define any event that can be triggered using asimilar syntax with respect to a property:
c l a s s d e f Rectangle < handle
eventsComputePerimeter
end
% Other d e f i n i t i o n s
end
At this point, it is possible to trigger this event whenever required:
func t ion p = compute_perimeter (obj )p = 2 * (obj .width + obj .height ) ;notify (obj , ' ComputePerimeter ' ) ;
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Events and notifications
Defining an event (2/3)
We keep track of how many times the function is called by using aninternal private counter:
p r o p e r t i e s (Access = private )nComputedPerimeter ;
end
We add a property to initialize the counter and link the event to itsspecific listener:
func t ion track_perimeter_method (obj )obj .nComputedPerimeter = 0 ;addlistener (obj , ' ComputePerimeter ' , @Rectangle .←↩
update_nComputedPerimeter ) ;end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Events and notifications
Defining an event (3/3)
Finally, we define the listener:
methods (Static )func t ion update_nComputedPerimeter (r , ˜ )
r .nComputedPerimeter = r .nComputedPerimeter + 1 ;end
end
We also need a function to print the result:
func t ion print_tracking_info (obj )f p r i n t f ( ' The ' ' ge t per ime ter ' ' func t ion has been c a l l e d %i times .\n '←↩
, obj .nComputedPerimeter ) ;end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Events and notifications
The event in action
>> r = Rectangle(3, 2);>> r.track_perimeter_method>> r.compute_perimeter;>> r.compute_perimeter;>> r.print_tracking_infoThe ’get_perimeter’ function has been called 2 times.>> r.nComputedPerimeterYou cannot get the ’nComputedPerimeter’ property of Rectangle.
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Overloading an operator
Overloading the times operator
By using OOP, it is possible to overload several basic MATLAB behav-iors for your custom object. As an example, we can overload the oper-ator ∗ for our rectangle class:
func t ion r = mtimes (obj1 ,obj2 )i f (isa (obj1 , ' Rectangle ' ) && isnumeric (obj2 ) )
r = obj1 .scale (obj2 ) ;e l s e i f (isnumeric (obj1 ) && isa (obj2 , ' Rectangle ' ) )
r = obj2 .scale (obj1 ) ;e l s e
e r r o r ( 'One operator must be a r e c t a n g l e and the other numeric ' ) ;end
end
Note that in our implementation we have to explicitly check for theorder of the operands. There is a large number of overloadable opera-tors: [MATLAB Operators and Associated Functions].
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Overloading an operator
Rectangle multiplication
>> r = Rectangle(3, 2);>> r = r*2r =
Rectangle with properties:
width: 6height: 4
>> r = 1/2*rr =
Rectangle with properties:
width: 3height: 2
>> r = ’a’*rError using Rectangle/mtimes (line 27)One operator must be a rectangle and the other numeric
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Overloading indexing
Indexing in MATLAB
Just like operators, every indexing operation in MATLAB has an asso-ciated function:
• subsref: subscripted reference, e.g. A(1:3) or A{1:3} orA.area.
• subsasgn: subscripted assignment, e.g. A(3) = 1.• subsindex: subscripted indexing using an object.
Each of these functions can be overloaded to implement custom be-havior.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Overloading indexing
Example: a class for damped oscillationsConsider the following class representing the function y = sin(x)
x .
c l a s s d e f DampedSinep r o p e r t i e s
limit ; % x−l i m i t f o r funct ionendmethods
funct ion obj = DampedSine (limit )obj .limit = limit ;
endfunct ion v = get_value (obj , x )
% Get the value of the funct ioni f ( any (x < 0) | | any (x > obj .limit ) )
e r r o r ( ' Argument i s outs ide s p e c i f i e d bounds ' ) ;endv = s in (x ) ./x ;
endfunct ion p l o t (obj )
% P l o t the funct ionx = 0 : 0 . 0 1 : obj .limit ; p l o t (x , obj .get_value (x ) ) ;
endend
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Overloading indexing
Overloading indexingWe can implement a custom indexing operation to create a sort of“callable” object:
func t ion B = subsref (A ,S )i f ( strcmp (S ( 1 ) . type , ' ( ) ' ) && length (S ( 1 ) .subs ) == 1)
B = A .get_value (S ( 1 ) .subs{1}) ;i f ( length (S ) > 1)
B = builtin ( ' subsre f ' , B , S ( 2 : end ) ) ;end
e l s eB = builtin ( ' subsre f ' , A , S ) ;
endend
>> ds = DampedSine(20);>> ds.get_value(5)ans =
-0.1918>> ds(5)ans =
-0.1918
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Custom displaying
Custom displaying
You can overload how a variable is displayed on the console:
func t ion disp (obj )f p r i n t f ( ' Rectangle with width=%.2 f and height =%.2 f\n ' , obj .width , ←↩
obj .height ) ;end
>> r = Rectangle(3, 2)
r =
Rectangle with width=3.00 and height=2.00
There are many other custom behaviors that you can implement: [Cus-tomize MATLAB Behavior].
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Inheritance and Polymorphism
What is inheritance?
• Inheritance is a feature of OOP languages that lets one class to‘inherits’ the behavior from a specific super-class.
• This allows a strong amount of code reuse, and the possibility ofcreating hierarchies of classes for your application (e.g. thehierarchy of data types in MATLAB).
• You can think of class B inheriting from class A as theimplementation of the semantic “B is-a A” (not to be confusedwith the classical “B has-a A”).
• Closely connected is the idea of polymorphism: a single interfaceis declined in multiple forms, and the specific implementation isdecided only at run-time.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Inheritance and Polymorphism
An example of inheritance
A square “is-a” rectangle, whose width and height are equivalent:
c l a s s d e f Square < Rectangle
p r o p e r t i e send
methods
funct ion obj = Square (l )obj = obj@Rectangle (l , l ) ;
end
end
end
Note the syntax of the call to a constructor of the super-class.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Inheritance and Polymorphism
Method overridingThe class Square inherits all the behavior of its superclass, thus allow-ing a strong amount of code reusing between implementations:
>> s = Square(3);>> s.compute_perimeter
ans =12
You can also override a specific method (in this case, for computationalreasons):
c l a s s d e f Square < Rectangle% . . .methods
% . . .func t ion p = compute_perimeter (obj )
p = 4*obj .height ;end
endend
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Inheritance and Polymorphism
Adding methods to the subclassYou can define methods that are exclusive of a particular subclass:
c l a s s d e f Square < Rectangle% . . .methods
% . . .func t ion l = get_length (obj )
l = obj .width ;end
endend
>> s = Square(3);>> s.get_lengthans =
3>> r = Rectangle(3, 2);>> r.get_lengthNo appropriate method, property, or field
get_length for class Rectangle.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Inheritance and Polymorphism
Sealed and protected attributes
You can specify that a property (or method) is accessible only to classesinheriting the super-class:
c l a s s d e f Ap r o p e r t i e s (Access=protected )
foo ;end
end
Additionally, you can specify that a particular class cannot be inher-ited from:
c l a s s d e f A (Sealed = true )% . . .
endc l a s s d e f B < A
% ERRORend
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Abstract classes
Abstract classes
Inheritance allows to define abstract classes. These cannot be instanti-ated, but they can:
• Abstract code from any specific sub-class.• Provide an interface for a set of functions that any sub-class must
implement.
Let us consider the following class hierarchy:
Shape (Abstract)
Rectangle
Square
Circle
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Abstract classes
Defining the abstract class
c l a s s d e f Shapep r o p e r t i e s
n_sides ; % Number of s i d e send
methods (Abstract=true )p = compute_perimeter (obj ) ; % Compute the perimeterobj = scale (obj , n ) ; % S c a l e the o b j e c t
end
methodsfunct ion obj = Shape (n )
obj .n_sides = n ;endfunct ion print_info (obj )
f p r i n t f ( ' This i s a geometric shape with %.2 f s i d e s .\n ' , obj←↩.n_sides ) ;
endend
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Abstract classes
Defining the first sub-class
c l a s s d e f Rectangle < Shapep r o p e r t i e s
width ; % Width of the r e c t a n g l eheight ; % Height of the r e c t a n g l e
endmethods
funct ion obj = Rectangle (w , h )obj = obj@Shape ( 4 ) ;obj .width = w ;obj .height = h ;
end
funct ion obj = scale (obj , n )obj .width = n*obj .width ;obj .height = n*obj .height ;
end
funct ion p = compute_perimeter (obj )p = 2 * (obj .width + obj .height ) ;
endend
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Abstract classes
Defining a new sub-class
Note: the class for the Square is unchanged with respect to before.
c l a s s d e f Circle < Shapep r o p e r t i e s
radius ; % Radius of the c i r c l eendmethods
funct ion obj = Circle (r )obj = obj@Shape ( I n f ) ;obj .radius = r ;
end
funct ion obj = scale (obj , n )obj .radius = n*obj .radius ;
end
funct ion p = compute_perimeter (obj )p = 2* pi *obj .radius ;
endend
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Abstract classes
Using the class hierarchy
>> r = Rectangle(3,2);>> r.scale(2)
ans =
Rectangle with properties:
width: 6height: 4n_sides: 4
>> s = Shape(3);Error using ShapeAbstract classes cannot be instantiated.
Class ’Shape’ defines abstract methods and/or properties.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Abstract classes
Refactoring
We can see that the code of the scale method is semantically equiva-lent in all cases: it multiplies by n all properties, except the number ofsides. We can, in principle, abstract this into the class Shape to providea default implementation:
c l a s s d e f Shape% . . .func t ion obj = scale (obj , n )
pr = p r o p e r t i e s (class (obj ) ) ;f o r ii = 1 : length (pr )
i f ( ˜ strcmp (pr{ii} , ' n s i d e s ' ) )obj . ( pr{ii}) = n*obj . ( pr{ii}) ;
endend
end% . . .
end
This is known as code refactoring.
Overview1 FUNDAMENTALS OF OOP
What is OOP?Syntax: defining a basic class
2 MORE OOPStatic and private elementsClass documentationHandle and Value classesEvents and notifications
3 CUSTOM MATLAB BEHAVIOROverloading an operatorOverloading indexingCustom displaying
4 INHERITANCEInheritance and PolymorphismAbstract classes
5 EXAMPLESimple Filtering Application
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Description of the example
As a final example, we implement a relatively simple (but with lotof possible extensions) filtering application. We have the followingspecifics:
• A class for generating the underlying system to be identified. Forsimplicity, the system is supposed to be linear, and the outputcorrupted with Gaussian noise.
• An abstract class for implementing any linear adaptive filter.One particular implementation of this class implementing thestandard LMS filter with constant step size.
• One class taking care of plotting the results. For simplicity, weimplement only one method for plotting the MSE in logarithmicscale.
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Signal generation
c l a s s d e f SignalGenerator% SignalGenerator − Class f o r generat ing input and output s i g n a l s
p r o p e r t i e staps ; % taps of the f i l t e rnoise_var ; % var iance of the noisewo ; % optimal weights of the l i n e a r system
end
methods
funct ion obj = SignalGenerator (taps , noise_var )obj .taps = taps ;i f ( nargin < 2)
obj .noise_var = 0 . 0 1 ;e l s e
obj .noise_var = noise_var ;endobj .wo = rand (taps , 1 ) *2 − 1 ;
end
endend
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Signal generation (cntd)
c l a s s d e f SignalGenerator% . . .
func t ion [X , d ] = generate_signal (obj , N )
% Generate s i g n a l of length N% The outputs are :% X : a NxM input matrix , where M i s the number of taps% d : a Nx1 vec tor of output values , corrupted by noise
X = randn (N , obj .taps ) ;d = X*obj .wo + randn (N , 1 ) * s q r t (obj .noise_var ) ;
end
% . . .end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Abstract class for filters
c l a s s d e f AdaptiveFilter% A d a p t i v e F i l t e r − Abstrac t c l a s s f o r adaptive f i l t e r s
p r o p e r t i e sw_estimated ; % Estimated weightserror_history ; % Vector of a−p r i o r i e r r o r s
end
methodsfunct ion obj = AdaptiveFilter (taps )
obj .w_estimated = zeros (taps , 1 ) ;end
% Here we need :% 1) one funct ion f o r process ing the f u l l d a t a s e t one item% at a time .% 2) one ( a b s t r a c t ) func t ion f o r implementing the s i n g l e% adaptat ion step .
end
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Abstract class for filters (cntd)
c l a s s d e f AdaptiveFilter% . . .methods
% . . .func t ion obj = process (obj , X , d )
% Process the o v e r a l l s i g n a l X/dN = length (d ) ;obj .error_history = zeros (N , 1 ) ;f o r ii = 1 :N
obj .error_history (ii ) = d (ii ) − X (ii , : ) *obj .←↩w_estimated ;
obj = obj .adapt (X (ii , : ) ' , d (ii ) , obj .error_history (ii )←↩) ;
endend
end
methods (Abstract )obj = adapt (obj , x , y , e ) ; % Signa l adaptat ion step
end
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Least Mean-Square Filter
c l a s s d e f LMSFilter < AdaptiveFilter% LmsFi l ter − Least Mean−Square adaptive f i l t e r with constant s tep ←↩
s i z e
p r o p e r t i e sstep_size ; % Step s i z e
end
methodsfunct ion obj = LMSFilter (taps , step_size )
obj = obj@AdaptiveFilter (taps ) ;obj .step_size = step_size ;
endfunct ion obj = adapt (obj , x , ˜ , e )
obj .w_estimated = obj .w_estimated + obj .step_size*e*x ;end
end
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Helper function for plotting
c l a s s d e f PlotHelper% PlotHelper − Helper c l a s s f o r p l o t t i n g
p r o p e r t i e s (Constant )font_size = 8 ; % Fonts izefont_size_leg = 6 ; % Font s i z e ( legend )font_name = 'TimesNewRoman ' ; % Font nameline_width = 1 ; % LineWidth
end
methods (Static )
func t ion plot_MSE_db (xlab , ylab , leg , varargin )% Inputs are : x−l a b e l y−l a b e l , c e l l array of s t r i n g s f o r ←↩
the% legend . Each a d d i t i o n a l input i s a time−s e r i e s to be ←↩
p l o t t e d .
% Code goes hereend
end
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Helper function for plotting (cntd)
func t ion plot_MSE_db (xlab , ylab , leg , varargin )% Each a d d i t i o n a l argument i s a time s e r i e s to be p l o t t e d
% Simple f i l t e r f o r smoothing the r e s u l t s[bb , aa ] = butter ( 2 , 0 . 0 2 ) ;
N_series = length (varargin ) ;
cmap = hsv (N_series ) ;f i g u r e ( ) ; hold on ; box on ; gr id on ;
f o r ii = 1 :N_seriesp l o t ( f i l t e r (bb , aa , 10* log10 (varargin{ii} . ˆ 2 ) ) , ' LineWidth ' , ←↩
PlotHelper .line_width , ' Color ' , cmap (ii , : ) ) ;end
x l a b e l (xlab , ' FontSize ' , PlotHelper .font_size , ' FontName ' , ←↩PlotHelper .font_name ) ;
y l a b e l (ylab , ' FontSize ' , PlotHelper .font_size , ' FontName ' , ←↩PlotHelper .font_name ) ;
legend (leg , ' FontSize ' , PlotHelper .font_size , ' FontName ' , ←↩PlotHelper .font_name ) ;
end
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Testing the application
% Repeatable experimentrng ( 1 ) ;
% Generate data f o r s imulat ionsg = SignalGenerator ( 5 , 0 . 1 ) ;[X , y ] = sg .generate_signal ( 5 0 0 0 ) ;
% Create two f i l t e r sf1 = LMSFilter ( 5 , 0 . 0 1 ) ;f2 = LMSFilter ( 5 , 0 . 0 0 1 ) ;
% Adapt the f i l t e rf1 = f1 .process (X , y ) ;f2 = f2 .process (X , y ) ;
% P l o tPlotHelper .plot_MSE_db ( ' Sample ' , 'MSE ' , { ' F i l t e r 1 ' , ' F i l t e r 2 ' } , f1 .←↩
error_history , f2 .error_history ) ;
FUNDAMENTALS OF OOP MORE OOP CUSTOM MATLAB BEHAVIOR INHERITANCE EXAMPLE
Simple Filtering Application
Result
0 500 1000 1500 2000 2500 3000 3500 4000 4500 5000−20
−15
−10
−5
0
5
Sample
MS
E
Filter 1
Filter 2
Top Related