Title: OOP Programming in Matlab
1OOP Programming in Matlab
Learning Objectives We will continue exploring
objects and will construct a subclass called
STOCK from the parent ASSET class
Topics
- Review our ASSET class and study how it might be
used as a parent for other classes - Extend the ASSET class to a subclass of STOCK
- Consider others like BONDS SAVINGS.
2Creating a Subclass
- Our ASSET class is of limited use because we will
need to use it to describe many different kinds
of assets - We could simply keep adding more properties to
cover all situations we might encounter - but this makes for very messy objects with lots
of unused or unknown (and therefore dangerous)
data - A more elegant way to handle this problem is to
create a subclass of ASSET for each type of asset
we might work with. - Consider a STOCK subclass of ASSET
- We will want to include the number of shares and
the share price - Well also need to update the CurrentValue
property in the parent ASSET object
3Creating the STOCK Subclass
- STOCK will be a subclass (child) of ASSET
- Create an _at_STOCK directory in WORK for class files
function s stock(varargin) STOCK Stock class
constructor sstock(descriptor, num_shares,
share_price) switch nargin case 0 no
arguments so create default object
s.num_shares 0 s.share_price 0 a
asset('none',0) create dummy object to define
parent class s class(s,'stock',a) create
STOCK object as subclass of ASSET case 1
single argument so make copy if
(isa(varargin1,'stock')) s
varargin1 else error('STOCK Input
argument is not a STOCK object') end case 3
s.num_shares varargin2 s.share_price
varargin3 current_value s.num_shares .
s.share_price a asset(varargin1,current_v
alue) create parent object s
class(s,'stock',a) create STOCK object as
child of parent otherwise error('STOCK Wrong
number of input arguments.') end
define the STOCK properties
create a parent object
now create the STOCK child object
Note parent object must be created with
specified property values
4STOCK display Method
- Just like display() for ASSET
First display parent property values
function display(s) DISPLAY(a) displays a
STOCK object display(s.asset) display
properties in parent object str sprintf('Number
of shares g\nShare Price 3.2f\n',...
s.num_shares, s.share_price) disp(str)
Then display subclass property values
- NOTE the 3rd line shows how you access
properties in another object (obj_name.obj_type)
5STOCK get Method
Display object properties
function val get(s, prop_name) GET Get STOCK
properties from specified object if nargin1
list objects properties if only object is given
disp('STOCK properties') disp('
Descriptor, Date, NumberShares, SharePrice,
CurrentValue') return end if
ischar(prop_name), error('GET prop_name must be
string.'), end prop_name lower(prop_name(islette
r(prop_name))) remove nonletters if
(length(prop_name) lt 2), error('GET prop_name
must be at least 2 chars.'), end switch
prop_name(12) case 'nu' val
s.num_shares case 'sh' val
s.share_price case 'de' val
get(s.asset,'descriptor') call ASSET GET
method case 'da' val get(s.asset,'date')
call ASSET GET method case 'cu' val
get(s.asset,'current_value') call ASSET GET
method otherwise error('GET ',prop_name,'
is not a valid asset property.') end
get STOCK properties
get parent ASSET properties using its SET method
6STOCK set Method
- Must define which properties can be set and which
will be computed - Providing error checking is IMPORTANT
function s set(s,varargin) SET set STOCK
properties and return updated object. Use
xyzstock(xyz,'prop_name', value,...)
(Note you must assign results to same or new
object) stock(xyz) returns list of
settable properties. if nargin1 list
settable properties if only object is given
disp('STOCK properties') disp(' Descriptor,
Date, NumberShares, SharePrice,
CurrentValue') return end if rem(nargin,2)
1 error('SET prop_name, values must be
provided in pairs.') end
Display object properties if only object is given
Make sure that proper number of arguments are
provided
continued on next slide
7STOCK set Method (contd)
for k22nargin-1 prop_name
varargink-1 if ischar(prop_name),
error('SET prop_name must be string.'), end
prop_name lower(prop_name(isletter(prop_name)))
remove nonletters value varargink
switch prop_name(12) case 'nu'
s.num_shares value case 'sh'
s.share_price value case 'de'
s.asset set(s.asset,'descriptor',value) set
parent property otherwise error('SET
invalid prop_name provided.') end end
update current value of stock in parent value
s.num_shares . s.share_price s.asset
set(s.asset,'CurrentValue',value,'Date',date)
Set properties in STOCK object
Set property in parent ASSET object
Must compute STOCK value and then set in parent
field
Note that not all properties can or should be
settable!
8Examples
- Here we create a STOCK object with initial values
and then use the SET method to update the price.
gtgt s1stock('Intel',25,15) Descriptor
Intel Date 03-Dec-2001 Current Value
375.00 Number of shares 25 Share Price
15.00 gtgt set(s1) STOCK properties
Descriptor, Date, NumberShares, SharePrice,
CurrentValue gtgt s1set(s1,'SharePrice',
20) Descriptor Intel Date 03-Dec-2001 Current
Value 500.00 Number of shares 25 Share Price
20.00
Note that SET reports the settable properties for
this calling syntax
9Example Changing Property Values
- Use set to change a property value
- REMEMBER you must reassign the output to the
object or the change will not be permanent!
Update the share price
gtgt set(s1,'SharePrice', 30) Descriptor
Intel Date 03-Dec-2001 Current Value
750.00 Number of shares 25 Share Price
30.00 gtgt display(s1) Descriptor Intel Date
03-Dec-2001 Current Value 500.00 Number of
shares 25 Share Price 20.00
It is reported in the automatic display when no
semicolon is provided
But if you try a subsequent display(), the price
was not changed!
10Creating the subsref Method
- In order to be able to access STOCK fields using
Matlabs array indexing or structure field
notation, we must define subsref for this class
function b subsref(s, index) SUBSREF Define
field name indexing for STOCK objects fc
fieldcount(s.asset) find out how many fields
are in parent object switch index.type case '()'
if (index.subs lt fc) b
subsref(s.asset,index) else switch
index.subs - fc case 1 b
s.num_shares case 2 b
s.share_price otherwise
error('SUBSREF Index must be in range 1 to
',num2str(fc2)) end end case '.'
switch index.subs case 'num_shares'
b s.num_shares case 'share_price'
b s.share_price otherwise b
subsref(s.asset,index) end case ''
error('SUBSREF Cell array indexing not supported
for STOCK objects.') end
Each case defines a different type of indexing
array, field, or cell
See Matlab documentation for further explanation
of this method
11Creating the subsasgn Method
- In order to be able to assign values to STOCK
fields using Matlabs array indexing or structure
field notation, we must define subsasgn for this
class
function s subsasgn(s, index, val) SUBSASGN
Define index assignment for STOCK objects fc
fieldcount(s.asset) get fields in parent
object switch index.type case '()' if
(index.subs lt fc) s.asset
subsasgn(s.asset,index,val) else
switch index.subs - fc case 1
s.num_shares val case 2
s.share_price val otherwise
error('SUBSASGN Index must be in range 1 to
',num2str(fc2)) end end case '.'
switch index.subs case 'num_shares'
s.num_shares val case 'share_price'
s.share_price val otherwise
s.asset subsasgn(s.asset,index,val)
end case '' error('SUBSASGN Cell array
indexing not supported for asset objects.') end
Each case defined a different type of indexing
array, field, or cell
See Matlab documentation for further explanation
of this method
12Example Using subsref
- Well create a STOCK object and then access its
properties using array indexing
gtgt s2stock('oracle',20,35) Descriptor
oracle Date 03-Dec-2001 Current Value
700.00 Number of shares 20 Share Price 35.00 gtgt
s2(1) ans oracle gtgt s2(4) ans 20 gtgt
s2.share_price ans 35 gtgt s21 ??? Error
using gt stock/subsref SUBSREF Cell array
indexing not supported for STOCK objects.
Access the first property using array indexing
The 4-th property is the number of shares
You can also use the internal field names (if you
know them)
Note that we didnt define cell indexing for our
STOCK objects
13Other Methods for STOCK
- While these methods provide powerful capabilities
for our new objects, there are some other methods
we might want to consider - Methods to convert the data from one form into
another - convert between different numeric formats like
double and int32 - this is more important for a simple class like
char or double - Method to convert the data into a string or cell
array - toString is a common OOP method name for this
purpose - converting to a cell array may be more useful
when an object contains many different fields - We will have to create loadobj and saveobj
methods if we want to be able to save our objects
to a .mat file along with the rest of the
workspace
14Where to from Here?
- With only a little modification we can create an
entirely new subclass that is based on our STOCK
class - We can do this by specifying that our new class
will inherit the structure and methods from a
parent or superclass (or from several parent
classes). - This is called inheritance and is an important
feature of OOP. - Consider a BOND class
- It has an identical structure to a STOCK,
- But there will be different properties
- We will create new display, get and set methods
- We will use the set and get methods from ASSET to
modify properties in the parent
15Summary
- OOP has let us create an entirely new data type
in Matlab - this is done by creating a class to define this
data type - we must also create all the methods (functions)
that can be used with this special data type - the internal details are hidden inside the class
- What else could we do with these new classes?
- A portfolio might contain a mix of STOCK, BOND
and SAVINGS assest How can we keep this
together? - AGGREGATION allows us to construct a new class
whose contents are objects from other classes - See Matlab reference docs for an example of how
to do this.
16Summary
- Learning Objectives
- OOP concepts
- STOCK subclasse
- Other subclasses
- Aggregation
- Summary
- Action Items
- Review the lecture
- Perform the exercises
- See if you can create the BOND class and get it
working like we did for the STOCK class. - Consider how this might be extended to other
applications