Matlab Objectoriented Programming Mathworks instant download
Matlab Objectoriented Programming Mathworks instant download
download
https://ebookbell.com/product/matlab-objectoriented-programming-
mathworks-49473930
https://ebookbell.com/product/a-guide-to-matlab-objectoriented-
programming-andy-h-register-5249872
https://ebookbell.com/product/matlab-a-practical-introduction-to-
programming-and-problem-solving-6th-edition-stormy-attaway-46075418
https://ebookbell.com/product/matlab-for-engineering-
applications-5e-ise-5thise-william-j-palm-iii-46562738
Matlab And Simulink Crash Course For Engineers 1st Ed 2022 Eklas
Hossain
https://ebookbell.com/product/matlab-and-simulink-crash-course-for-
engineers-1st-ed-2022-eklas-hossain-46608958
Matlab Medical Imaging Toolbox Users Guide The Mathworks
https://ebookbell.com/product/matlab-medical-imaging-toolbox-users-
guide-the-mathworks-46611260
https://ebookbell.com/product/matlab-for-engineering-applications-5th-
edition-william-palm-46651690
https://ebookbell.com/product/matlab-for-engineering-berardino-
dacunto-48710470
https://ebookbell.com/product/matlab-for-medical-physics-reallife-
clinical-scenarios-and-projects-jidi-sun-49034592
Matlab For Engineering And The Life Sciences 2nd Edition Joe
Tranquillo
https://ebookbell.com/product/matlab-for-engineering-and-the-life-
sciences-2nd-edition-joe-tranquillo-49437374
MATLAB®
Object-Oriented Programming
R2023a
How to Contact MathWorks
Phone: 508-647-7000
Basic Example
2
Creating a Simple Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Design Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Create Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Access Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Call Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Add Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Vectorize Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Overload Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
BasicClass Code Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
v
Using BankAccount Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12
Static Data
4
Static Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
What Is Static Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Static Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Static Data Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Constant Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4
vi Contents
Special Considerations for Validation in Methods . . . . . . . . . . . . . . . . . . 5-10
vii
Defining and Organizing Classes
6
User-Defined Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
What Is a Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Attributes for Class Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Kinds of Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Constructing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Class Hierarchies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
classdef Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Class Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
viii Contents
Creating and Managing Class Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-27
Creating an Alias Definition File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-27
Viewing Alias Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-28
Backward and Forward Compatibility of Aliases . . . . . . . . . . . . . . . . . . . 6-28
ix
Implement Copy for Handle Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-30
Copy Method for Handle Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-30
Customize Copy Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-31
Copy Properties That Contain Handles . . . . . . . . . . . . . . . . . . . . . . . . . . 7-32
Exclude Properties from Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33
x Contents
Property Get and Set Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-38
Property Get Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-38
Property Set Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
xi
Define Method in Function File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8
Specify Method Attributes in classdef File . . . . . . . . . . . . . . . . . . . . . . . . 9-9
Methods You Must Define in the classdef File . . . . . . . . . . . . . . . . . . . . . 9-10
Object Arrays
10
Construct Object Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Build Arrays in the Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Referencing Property Values in Object Arrays . . . . . . . . . . . . . . . . . . . . . 10-2
xii Contents
Initialize Object Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-5
Calls to Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-5
Initial Value of Object Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6
xiii
Create Listener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-3
xiv Contents
Listen for Changes to Property Values . . . . . . . . . . . . . . . . . . . . . . . . . . 11-32
Create Property Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-32
Property Event and Listener Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-33
xv
Modify Inherited Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-17
Superclass Property Modification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-17
Private Local Property Takes Precedence in Method . . . . . . . . . . . . . . . 12-17
xvi Contents
Built-In Data Value Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-44
Built-In Data Organization Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-44
Built-In Indexing Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-45
Built-In Concatenation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-45
xvii
Reduce MAT-File Size for Saved Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Default Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Dependent Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Transient Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Avoid Saving Unwanted Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
xviii Contents
Enumerations
14
Named Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
Kinds of Predefined Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
Techniques for Defining Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
xix
Handle-Based Enumeration Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-33
Represent State with Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-35
Constant Properties
15
Define Class Properties with Constant Values . . . . . . . . . . . . . . . . . . . . . . 15-2
Defining Named Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2
Constant Property Assigned a Handle Object . . . . . . . . . . . . . . . . . . . . . 15-3
Constant Property Assigned Any Object . . . . . . . . . . . . . . . . . . . . . . . . . 15-4
Constant Properties — No Support for Get Events . . . . . . . . . . . . . . . . . 15-5
xx Contents
Specialize Object Behavior
17
Methods That Modify Default Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
How to Customize Class Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Which Methods Control Which Behaviors . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Overload Functions and Override Methods . . . . . . . . . . . . . . . . . . . . . . . 17-3
xxi
Customizing Object Display
18
Custom Display Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
Command Window Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
Default Object Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
CustomDisplay Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-3
Methods for Customizing Object Display . . . . . . . . . . . . . . . . . . . . . . . . . 18-3
xxii Contents
Overloading the disp Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-34
Display Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-34
Overloaded disp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-34
Relationship Between disp and display . . . . . . . . . . . . . . . . . . . . . . . . . 18-34
xxiii
1
The MATLAB language enables you to create programs using both procedural and object-oriented
techniques and to use objects and ordinary functions together in your programs.
In procedural programming, your design focuses on the steps that must execute to achieve a desired
state. Typically, you represent data as individual variables or fields of a structure. You implement
operations as functions that take the variables as arguments. Programs usually call a sequence of
functions, each one of which is passed data, and then returns modified data. Each function performs
an operation or many operations on the data.
• Identifying the components of the system or application that you want to build
• Analyzing and identifying patterns to determine what components are used repeatedly or share
characteristics
• Classifying components based on similarities and differences
After performing this analysis, you define classes that describe the objects your application uses.
A class describes a set of objects with common characteristics. Objects are specific instances of a
class. The values contained in an object's properties are what make an object different from other
objects of the same class. The functions defined by the class (called methods) are what implement
object behaviors that are common to all objects of a class.
As functions become too large, you can break them into smaller functions and pass data from one to
function to another. However, as the number of functions becomes large, designing, and managing
the data passed to functions becomes difficult and error prone. At this point, consider moving your
MATLAB programming tasks to object-oriented designs.
1-2
Why Use Object-Oriented Design
Thinking in terms of objects is simpler and more natural for some problems. Think of the nouns in
your problem statement as the objects to define and the verbs as the operations to perform.
Consider the design of classes to represent money lending institutions (banks, mortgage companies,
individual money lenders, and so on). It is difficult to represent the various types of lenders as
procedures. However, you can represent each one as an object that performs certain actions and
contains certain data. The process of designing the objects involves identifying the characteristics of
a lender that are important to your application.
Identify Commonalities
What do all money lenders have in common? All MoneyLender objects can have a loan method and
an InterestRate property, for example.
Identify Differences
How does each money lender differ? One can provide loans to businesses while another provides
loans only to individuals. Therefore, the loan operation might need to be different for different types
of lending institutions. Subclasses of a base MoneyLender class can specialize the subclass versions
of the loan method. Each lender can have a different value for its InterestRate property.
Factor out commonalities into a superclass and implement what is specific to each type of lender in
the subclass.
Add Only What Is Necessary
These institutions might engage in activities that are not of interest to your application. During the
design phase, determine what operations and data an object must contain based on your problem
definition.
Objects provide several useful features not available from structures and cell arrays. For example,
objects can:
Reducing Redundancy
As the complexity of your program increases, the benefits of an object-oriented design become more
apparent. For example, suppose that you implement the following procedure as part of your
application:
1 Check inputs
2 Perform computation on the first input argument
3 Transform the result of step 2 based on the second input argument
4 Check validity of outputs and return values
You can implement this procedure as an ordinary function. But suppose that you use this procedure
again somewhere in your application, except that step 2 must perform a different computation. You
1-3
1 Using Object-Oriented Design in MATLAB
could copy and paste the first implementation, and then rewrite step 2. Or you could create a function
that accepted an option indicating which computation to make, and so on. However, these options
lead to more complicated code.
An object-oriented design can factor out the common code into what is called a base class. The base
class would define the algorithm used and implement whatever is common to all cases that use this
code. Step 2 could be defined syntactically, but not implemented, leaving the specialized
implementation to the classes that you then derive from this base class.
Step 1
function checkInputs()
% actual implementation
end
Step 2
function results = computeOnFirstArg()
% specify syntax only
end
Step 3
function transformResults()
% actual implementation
end
Step 4
function out = checkOutputs()
% actual implementation
end
The code in the base class is not copied or modified. Classes you derive from the base class inherit
this code. Inheritance reduces the amount of code to be tested, and isolates your program from
changes to the basic procedure.
The use of a class as the basis for similar, but more specialized classes is a useful technique in object-
oriented programming. This class defines a common interface. Incorporating this kind of class into
your program design enables you to:
Reducing Complexity
Objects reduce complexity by reducing what you must know to use a component or system:
To illustrate these advantages, consider the implementation of a data structure called a doubly linked
list. See “Implementing Linked Lists with Classes” on page 3-23 for the actual implementation.
1-4
Why Use Object-Oriented Design
To add a node to the list, disconnect the existing nodes in the list, insert the new node, and reconnect
the nodes appropriately. Here are the basic steps:
Now create the new node, connect it, and renumber the original nodes:
1 Link new.Prev to n1
2 Link new.Next to n3 (was n2)
3 Link n1.Next to new (will be n2)
4 Link n3.Prev to new (will be n2)
The details of how methods perform these steps are encapsulated in the class design. Each node
object contains the functionality to insert itself into or remove itself from the list.
For example, in this class, every node object has an insertAfter method. To add a node to a list,
create the node object and then call its insertAfter method:
nnew = NodeConstructor;
nnew.insertAfter(n1)
Because the node class defines the code that implements these operations, this code is:
The object methods enforce the rules for how the nodes interact. This design removes the
responsibility for enforcing rules from the applications that use the objects. It also means that the
application is less likely to generate errors in its own implementation of the process.
1-5
1 Using Object-Oriented Design in MATLAB
Fostering Modularity
As you decompose a system into objects (car –> engine –> fuel system –> oxygen sensor), you form
modules around natural boundaries. Classes provide three levels of control over code modularity:
• Public — Any code can access this particular property or call this method.
• Protected — Only this object's methods and methods of objects derived from this object's class can
access this property or call this method.
• Private — Only the object's own methods can access this property or call this method.
When you define a class, you can overload existing MATLAB functions to work with your new object.
For example, the MATLAB serial port class overloads the fread function to read data from the device
connected to the port represented by this object. You can define various operations, such as equality
(eq) or addition (plus), for a class you have defined to represent your data.
See Also
More About
• “Role of Classes in MATLAB” on page 3-2
1-6
Handle Object Behavior
More than one variable can refer to the same handle object. Therefore, users interact with instances
of handle classes differently than instances of value classes. Understanding how handle objects
behave can help you determine whether to implement a handle or a value class. This topic illustrates
some of those interactions.
What Is a Handle?
Certain kinds of MATLAB objects are handles. When a variable holds a handle, it actually holds a
reference to the object.
Handle objects enable more than one variable to refer to the same object. Handle-object behavior
affects what happens when you copy handle objects and when you pass them to functions.
Copies of Handles
All copies of a handle object variable refer to the same underlying object. This reference behavior
means that if h identifies a handle object, then,
h2 = h;
For example, the MATLAB audioplayer function creates a handle object that contains the audio
source data to reproduce a specific sound segment. The variable returned by the audioplayer
function identifies the audio data and enables you to access object functions to play the audio.
MATLAB software includes audio data that you can load and use to create an audioplayer object.
This sample load audio data, creates the audio player, and plays the audio:
load gong Fs y
gongSound = audioplayer(y,Fs);
play(gongSound)
Suppose that you copy the gongSound object handle to another variable (gongSound2):
gongSound2 = gongSound;
The variables gongSound and gongSound2 are copies of the same handle and, therefore, refer to the
same audio source. Access the audioplayer information using either variable.
1-7
1 Using Object-Oriented Design in MATLAB
For example, set the sample rate for the gong audio source by assigning a new value to the
SampleRate property. First get the current sample rate and then set a new sample rate:
sr = gongSound.SampleRate;
disp(sr)
8192
gongSound.SampleRate = sr*2;
disp(gongSound2.SampleRate)
16384
play(gongSound2)
Passing a nonhandle variable to a function does not affect the original variable that is in the caller’s
workspace. For example, myFunc modifies a local variable called var, but when the function ends,
the local variable var no longer exists:
function myFunc(var)
var = var + 1;
end
x = 12;
myFunc(x)
disp(x)
12
The myFunc function can return the modified value, which you could assign to the same variable
name (x) or another variable.
x = 12;
x = myFunc(x);
disp(x)
13
1-8
Handle Object Behavior
When the argument is a handle variable, the function copies only the handle, not the object identified
by that handle. Both handles (original and local copy) refer to the same object.
When the function modifies the data referred to by the object handle, those changes are accessible
from the handle variable in the calling workspace without the need to return the modified object.
For example, the modifySampleRate function changes the audioplayer sample rate:
function modifySampleRate(audioObj,sr)
audioObj.SampleRate = sr;
end
8192
modifySampleRate(gongSound,16384)
disp(gongSound.SampleRate)
16384
The modifySampleRate function does not need to return a modified gongSound object because
audioplayer objects are handle objects.
When a handle object has been deleted, the handle variables that referenced the object can still exist.
These variables become invalid because the object they referred to no longer exists. Calling delete
on the object removes the object, but does not clear handle variables.
The output argument, gongSound, is a handle variable. Calling delete deletes the object along with
the audio source information it contains:
1-9
1 Using Object-Oriented Design in MATLAB
delete(gongSound)
disp(gongSound)
whos
Fs 1x1 8 double
gongSound 1x1 0 audioplayer
y 42028x1 336224 double
Note The value for Bytes returned by the whos command does not include the data referenced by a
handle because many variables can reference the same data.
The handle gongSound no longer refers to a valid object, as shown by the isvalid handle method:
isvalid(gongSound)
ans =
logical
Calling delete on a deleted handle does nothing and does not cause an error. You can pass an array
containing both valid and invalid handles to delete. MATLAB deletes the valid handles, but does not
issue an error when encountering handles that are already invalid.
gongSound.SampleRate
play(gongSound)
clear gongSound
whos
Fs 1x1 8 double
y 42028x1 336224 double
1-10
Handle Object Behavior
See Also
More About
• “Handle Class Destructor” on page 7-13
• “Comparison of Handle and Value Classes” on page 7-2
1-11
2
Basic Example
2 Basic Example
In this section...
“Design Class” on page 2-2
“Create Object” on page 2-3
“Access Properties” on page 2-3
“Call Methods” on page 2-3
“Add Constructor” on page 2-4
“Vectorize Methods” on page 2-4
“Overload Functions” on page 2-5
“BasicClass Code Listing” on page 2-6
Design Class
The basic purpose of a class is to define an object that encapsulates data and the operations
performed on that data. For example, BasicClass defines a property and two methods that operate
on the data in that property:
• Value — Property that contains the numeric data stored in an object of the class
• roundOff — Method that rounds the value of the property to two decimal places
• multiplyBy — Method that multiplies the value of the property by the specified number
Start a class definition with a classdef ClassName...end block, and then define the class
properties and methods inside that block. Here is the definition of BasicClass:
classdef BasicClass
properties
Value {mustBeNumeric}
end
methods
function r = roundOff(obj)
r = round([obj.Value],2);
end
function r = multiplyBy(obj,n)
r = [obj.Value]*n;
end
end
end
• Save the class definition in a .m file with the same name as the class.
• Create an object of the class.
• Access the properties to assign data.
• Call methods to perform operation on the data.
2-2
Creating a Simple Class
Create Object
Create an object of the class using the class name:
a = BasicClass
a =
Value: []
Access Properties
Assign a value to the Value property using the object variable and a dot before the property name:
a.Value = pi/3;
a.Value
ans =
1.0472
Call Methods
Call the roundOff method on object a:
roundOff(a)
ans =
1.0500
Pass the object as the first argument to a method that takes multiple arguments, as in this call to the
multiplyBy method:
multiplyBy(a,3)
ans =
3.1416
a.multiplyBy(3)
Passing the object as an explicit argument is not necessary when using dot notation. The notation
uses the object to the left of the dot.
2-3
2 Basic Example
Add Constructor
Classes can define a special method to create objects of the class, called a constructor. Constructor
methods enable you to pass arguments to the constructor, which you can assign as property values.
The BasicClass Value property restricts its possible values using the mustBeNumeric function.
Here is a constructor for the BasicClass class. When you call the constructor with an input
argument, it is assigned to the Value property. If you call the constructor without an input argument,
the Value property has a default value of empty ([]).
methods
function obj = BasicClass(val)
if nargin == 1
obj.Value = val;
end
end
end
By adding this constructor to the class definition, you can create an object and set the property value
in one step:
a = BasicClass(pi/3)
a =
Value: 1.0472
The constructor can perform other operations related to creating objects of the class.
Vectorize Methods
MATLAB enables you to vectorize operations. For example, you can add a number to a vector:
[1 2 3] + 2
ans =
3 4 5
MATLAB adds the number 2 to each of the elements in the array [1 2 3]. To vectorize the
arithmetic operator methods, enclose the obj.Value property reference in brackets.
[obj.Value] + 2
This syntax enables the method to work with arrays of objects. For example, create an object array
using indexed assignment.
obj(1) = BasicClass(2.7984);
obj(2) = BasicClass(sin(pi/3));
obj(3) = BasicClass(7);
2-4
Creating a Simple Class
[obj.Value] + 2
[obj(1).Value obj(2).Value obj(3).Value] + 2
The roundOff method is vectorized because the property reference is enclosed in brackets.
r = round([obj.Value],2);
roundOff(obj)
ans =
Overload Functions
Classes can implement existing functionality, such as addition, by defining a method with the same
name as the existing MATLAB function. For example, suppose that you want to add two BasicClass
objects. It makes sense to add the values of the Value properties of each object.
Here is an overloaded version of the MATLAB plus function. It defines addition for the BasicClass
class as adding the property values:
methods
function r = plus(o1,o2)
r = [o1.Value] + [o2.Value];
end
end
By implementing a method called plus, you can use the “+” operator with objects of BasicClass.
a = BasicClass(pi/3);
b = BasicClass(pi/4);
a + b
ans =
1.8326
a = BasicClass(pi/3);
b = BasicClass(pi/4);
c = BasicClass(pi/2);
ar = [a b];
ar + c
ans =
2.6180 2.3562
Related Information
For information on overloading functions, see “Overload Functions in Class Definitions” on page 9-
25.
2-5
2 Basic Example
classdef BasicClass
properties
Value {mustBeNumeric}
end
methods
function obj = BasicClass(val)
if nargin == 1
obj.Value = val;
end
end
function r = roundOff(obj)
r = round([obj.Value],2);
end
function r = multiplyBy(obj,n)
r = [obj.Value] * n;
end
function r = plus(o1,o2)
r = [o1.Value] + [o2.Value];
end
end
end
See Also
Related Examples
• “Components of a Class” on page 5-2
• “Validate Property Values” on page 8-18
2-6
3
Classes
In the MATLAB language, every value is assigned to a class. For example, creating a variable with an
assignment statement constructs a variable of the appropriate class:
a = 7;
b = 'some text';
s.Name = 'Nancy';
s.Age = 64;
whos
whos
Name Size Bytes Class Attributes
a 1x1 8 double
b 1x9 18 char
s 1x1 370 struct
Basic commands like whos display the class of each value in the workspace. This information helps
MATLAB users recognize that some values are characters and display as text while other values are
double precision numbers, and so on. Some variables can contain different classes of values like
structures.
Predefined Classes
MATLAB defines fundamental classes that comprise the basic types used by the language. These
classes include numeric, logical, char, cell, struct, and function handle.
User-Defined Classes
You can create your own MATLAB classes. For example, you could define a class to represent
polynomials. This class could define the operations typically associated with MATLAB classes, like
addition, subtraction, indexing, displaying in the command window, and so on. These operations
would need to perform the equivalent of polynomial addition, polynomial subtraction, and so on. For
example, when you add two polynomial objects:
p1 + p2
the plus operation must be able to add polynomial objects because the polynomial class defines this
operation.
When you define a class, you can overload special MATLAB functions (such as plus.m for the
addition operator). MATLAB calls these methods when users apply those operations to objects of your
class.
See “Representing Polynomials with Classes” on page 19-2 for an example that creates just such a
class.
3-2
Role of Classes in MATLAB
MATLAB classes use the following words to describe different parts of a class definition and related
concepts.
Classes
A class is a definition that specifies certain characteristics that all instances of the class share. These
characteristics are determined by the properties, methods, and events that define the class and the
values of attributes that modify the behavior of each of these class components. Class definitions
describe how objects of the class are created and destroyed, what data the objects contain, and how
you can manipulate this data.
Class Hierarchies
It sometimes makes sense to define a new class in terms of existing classes. This approach enables
you to reuse the designs and techniques in a new class that represents a similar entity. You
accomplish this reuse by creating a subclass. A subclass defines objects that are a subset of those
objects defined by the superclass. A subclass is more specific than its superclass and might add new
properties, methods, and events to those components inherited from the superclass.
Mathematical sets can help illustrate the relationships among classes. In the following diagram, the
set of Positive Integers is a subset of the set of Integers and a subset of Positives. All three sets are
subsets of Reals, which is a subset of All Numbers.
The definition of Positive Integers requires the additional specification that members of the set be
greater than zero. Positive Integers combine the definitions from both Integers and Positives. The
resulting subset is more specific, and therefore more narrowly defined, than the supersets, but still
shares all the characteristics that define the supersets.
3-3
3 MATLAB Classes Overview
The “is a” relationship is a good way to determine if it is appropriate to define a particular subset in
terms of existing supersets. For example, each of the following statements makes senses:
If the “is a” relationship holds, then it is likely you can define a new class from a class or classes that
represent some more general case.
Reusing Solutions
Classes are usually organized into taxonomies to foster code reuse. For example, if you define a class
to implement an interface to the serial port of a computer, it would probably be similar to a class
designed to implement an interface to the parallel port. To reuse code, you could define a superclass
that contains everything that is common to the two types of ports, and then derive subclasses from
the superclass in which you implement only what is unique to each specific port. Then the subclasses
would inherit all the common functionality from the superclass.
Objects
A class is like a template for the creation of a specific instance of the class. This instance or object
contains actual data for a particular entity that is represented by the class. For example, an instance
of a bank account class is an object that represents a specific bank account, with an actual account
number and an actual balance. This object has built into it the ability to perform operations defined
by the class, such as making deposits to and withdrawals from the account balance.
Objects are not just passive data containers. Objects actively manage the data contained by allowing
only certain operations to be performed, by hiding data that does not need to be public, and by
preventing external clients from misusing data by performing operations for which the object was not
designed. Objects even control what happens when they are destroyed.
3-4
Role of Classes in MATLAB
Encapsulating Information
An important aspect of objects is that you can write software that accesses the information stored in
the object via its properties and methods without knowing anything about how that information is
stored, or even whether it is stored or calculated when queried. The object isolates code that
accesses the object from the internal implementation of methods and properties. You can define
classes that hide both data and operations from any methods that are not part of the class. You can
then implement whatever interface is most appropriate for the intended use.
References
[1] Shalloway, A., J. R. Trott, Design Patterns Explained A New Perspective on Object-Oriented
Design.. Boston, MA: Addison-Wesley 2002.
[2] Gamma, E., R. Helm, R. Johnson, J. Vlissides, Design Patterns Elements of Reusable Object-
Oriented Software. Boston, MA: Addison-Wesley 1995.
[3] Freeman, E., Elisabeth Freeman, Kathy Sierra, Bert Bates, Head First Design Patterns.
Sebastopol, CA 2004.
See Also
Related Examples
• “Creating a Simple Class” on page 2-2
• “Developing Classes That Work Together” on page 3-6
• “Representing Structured Data with Classes” on page 3-14
• “Implementing Linked Lists with Classes” on page 3-23
3-5
3 MATLAB Classes Overview
Formulating a Class
This example discusses how to approach the design and implementation of two classes that interact
through events and listeners. The two classes represent a bank account and an account manager.
To design a class that represents a bank account, first determine the elements of data and the
operations that form your abstraction of a bank account. For example, a bank account has:
• An account number
• An account balance
• A status (open, closed, etc.)
If the balance is too low and you attempt to withdraw money, the bank account broadcasts a notice.
When this event occurs, the bank account broadcasts a notice to other entities that are designed to
listen for these notices. In this example, a simplified version of an account manager program
performs this task.
In this example, an account manager program determines the status of all bank accounts. This
program monitors the account balance and assigns one of three values:
These features define the requirements of the BankAccount and AccountManager classes. Include
only what functionality is required to meet your specific objectives. Support special types of accounts
by subclassing BankAccount and adding more specific features to the subclasses. Extend the
AccountManager as required to support new account types.
3-6
Developing Classes That Work Together
Class Data
The class defines these properties to store the account number, account balance, and the account
status:
• AccountNumber — A property to store the number identifying the specific account. MATLAB
assigns a value to this property when you create an instance of the class. Only BankAccount class
methods can set this property. The SetAccess attribute is private.
• AccountBalance — A property to store the current balance of the account. The class operation
of depositing and withdrawing money assigns values to this property. Only BankAccount class
methods can set this property. The SetAccess attribute is private.
• AccountStatus — The BankAccount class defines a default value for this property. The
AccountManager class methods change this value whenever the value of the AccountBalance
falls below 0. The Access attribute specifies that only the AccountManager and BankAccount
classes have access to this property.
• AccountListener — Storage for the InsufficentFunds event listener. Saving a BankAccount
object does not save this property because you must recreate the listener when loading the object.
Class Operations
• BankAccount — Accepts an account number and an initial balance to create an object that
represents an account.
• deposit — Updates the AccountBalance property when a deposit transaction occurs
• withdraw — Updates the AccountBalance property when a withdrawal transaction occurs
• getStatement — Displays information about the account
• loadobj — Recreates the account manager listener when you load the object from a MAT-file.
Class Events
The account manager program changes the status of bank accounts that have negative balances. To
implement this action, the BankAccount class triggers an event when a withdrawal results in a
negative balance. Therefore, the triggering of the InsufficientsFunds event occurs from within
the withdraw method.
To define an event, specify a name within an events block. Trigger the event by a call to the notify
handle class method. Because InsufficientsFunds is not a predefined event, you can name it with
any char vector and trigger it with any action.
3-7
3 MATLAB Classes Overview
example, different values for the account balance. Therefore, implement the BankAccount class as a
handle class. All copies of a given handle object refer to the same data.
3-8
Random documents with unrelated
content Scribd suggests to you:
the band played the Star-spangled Banner. All this was done without
sound of any sort, save the sweet strains of the music, or the deeper
drawing of the breath, and yet the men of other nations uncovered
their heads in respectful acknowledgment of the fact that they stood
before the representatives of the truest and most patriotic country
on earth.
So many things crowd to the place where the gray matter should
be that I gasp for breath. I wonder if every woman who comes over
here is possessed with the wild desire to write letters. I go to places
now, that I may tell you about them, and am uneasy until I reach
my little sky-parlor in order to begin the telling.
Can I ever make you understand how much, how very much, I
appreciate all the delights you are making it possible for me to
enjoy? Were I to be stricken blind and deaf, and then live a
thousand years, I have enough of beauty of color, of sound and of
fragrance to enable me to live happily through it all. And yet, I am
going to say, "I told you so."
I find that one can get her linen washed quickly, cheaply and
well in all parts of England. You give your soiled clothes, with a
thru'pence, to your maid at night, and you will find them at your
door, along with your shoes, in the morning—shoes and all having
been thoroughly washed.
There is a system of "carted luggage" here by which one may
send any large piece of luggage that can be locked (it will not be
taken otherwise) from one's door and find it in one's room at the
hotel or lodgings in the next city. The cost is nominal. Unless one
comes to visit or for social duties, only the bare necessities should
be taken. Other articles are an extra bother and expense. We have
learned, too, to write in advance, in time for a reply, before
venturing to hotels or lodgings. Women unaccompanied by men do
not receive the best attention in Europe unless "expected."
TENNYSON'S HOUSE
The ride was all too short. It seemed but a moment until we
were stepping from the boat into the train at Ryde which was to
carry us the entire length of the island to Freshwater, twenty-three
miles away.
We arrived at Freshwater at sunset just as the bells were ringing
for vespers, and we walked with the country folk the half mile from
the station to the inn. Stopping long enough to leave our bags and
wraps, we continued across the meadows to Farringford, the
beautiful home of Tennyson. This was the realization of one of my
cherished desires.
It was with difficulty that I dragged myself away from this restful
spot, but I hope that I caught a bit of the inspiration that he found
there.
We had our tea in the garden of the little inn which nestles
under the wall of Carisbrooke Castle. After we had climbed to its
tower for the view and had returned to earth again, we continued on
to Newport and Ventnor.
STREET IN BONCHURCH
STOKE POGES:
As you sit under the yew tree where Gray sat and dreamed, you
will realize the significance of his immortal lines:
EN ROUTE:
EDINBURGH:
The picturesque "Old Town" begins with the castle on its huge
embankment and slopes down toward the south. It is here one finds
the historic landmarks crowding each other in dramatic interest.
Here, too, is brought vividly to mind the sad story of poor Queen
Mary.
In the valley between the old and new towns is found a wealth
of art and architecture not duplicated anywhere, for these Scots are
strong in their originality.
GLASGOW:
The big red coach, with its four white horses and red-coated
driver, meets the passengers as they alight from the traveling
carriages, and dashes away almost before they are seated. Then
follows in quick succession pictures of white roads bordered with
purple heather, with a background of the dark green of the
mountain; of a stone bridge spanning the blue waters of a salmon
stream; of a wild bit of mountain scenery, with a road seemingly
straight up its rugged sides; and last comes the view of the calm
waters of Loch Katrine.
The boat Rob Roy receives the party from the coach and rounds
Ellen's Isle, sailing almost the entire length of the beautiful loch.
When it finally lands, there is another coach waiting to carry us
across the mountains, and on to Inversnaid, where, after visiting the
waterfall, the train is taken for Glasgow.
B urns's land lies between Glasgow and the sea, and from the
moment that one alights from the train, at each step is found
some haunt of the much-loved poet. It takes but a short time to
peep through the window into the room where Burns was born, and
to compare the humble cot where he lived his life with the
magnificent place he occupies in death. His tomb is set high up on a
hill in the midst of a park whose sides slope down to the bonnie
Doon.
IRELAND
When the glass is up to thirty,
Be sure the weather will be dirty.
When the glass is high, O very!
There'll be rain in Cork or Kerry.
When the glass is low, O Lork!
There'll be rain in Kerry and Cork.
* * * * * *
And when the glass has climbed its best,
The sky'll be weeping in the west.
Kate Douglas Wiggin.
KILLARNEY:
I wish I were a poet! But even the poet laureate, who recently
visited here, says, "Words cannot do justice to this sweet, sad
scene." His word "sad" pleased me, for I said yesterday to Ruth that
the scenery of Ireland has a tenderness about it that makes one be
quiet and think things.
DUNLUCE CASTLE
We started at nine-thirty in a four-horse coach with a bugler. The
road lies along the north side of the lower lake, and it wasn't long
before the exquisite mountain scenery came into view. The Purple
Mountains grew more interesting at every step. Presently we came
to Kate Kearney's cottage, and our Irish guide turned and asked, in
the richest of brogues:
We left the ponies at the foot of the mountains and paid toll into
Lord Brandon's estate in order to reach the boats. Lunch was served
on the banks of the upper lake.
The upper lake is more placid and less changeable, but the lower
has every change, from smooth, glass-like waters to the rapids,
which we "shoot" in no fearless manner. Finally we alight on
Innisfallen Island to see the ruins of the abbey; then we cross to
Ross Castle. Here another coach and four was in waiting to carry us
home. After ten miles by coach, five on horseback and thirteen by
boat, I actually dress for dinner.
After breakfast the coach came dashing up, and away we flew
again, over the purple hills, through shady lanes, past the wee farms
and the hovels, catching glimpses of castles, churches and ruins.
The most beautiful of all is Muckross Abbey. I had no idea we could
possibly repeat the pleasures of yesterday, but in some respects we
exceeded them. Our road today wound up and around Eagle Nest
Mountain, in the dark recesses of which the eagle builds its nest.
Here, too, is the home of the famous Killarney echo. The effect
produced by the notes of a bugle is almost supernatural.
The literary Killarnian claims for this beautiful region that it was
the ruins of the old castle on the shores of the Middle Lake which
called forth Tennyson's masterpiece, "The Bugle Song."
The Purple Mountains take their name from the purple of the
heather. One can see every shade, from the light pink-lavender to
the dark, almost red, purple.
We arrived at Glengariff just as the sun was sinking. The valley,
the lakes, the mountains, the red coach, with its four big horses
darting in and out of the winding road, and finally galloping up to
the exquisite little inn at Glengariff, high on a knoll overlooking the
blue waters of the Bay of Bantry, are among the delightful details of
today's picture.
CORK:
When any one tells you that he kissed the Blarney stone, take it
with several grains of salt. It is a physical impossibility for one who
wears petticoats.
One of the pleasant drives from Cork takes one to Sir Walter
Raleigh's home at Youghal. For more than four hundred years it has
stood with but little change. Attached to the grounds is the garden
where Raleigh experimented with the potato, which here was first
grown in Ireland.
And so this all too happy summer must come to a close. I remain
here to study, and Ruth goes to Iceland. We shall meet in the spring,
when I shall have taken my degree (?), and go to sunny Italy
together.
It is said that to travel through Europe with one and still remain
friends, stamps both as remarkably amiable persons. Without
wishing to seem egotistical, I'd like you to know that before bidding
Ruth good-bye she invited me to join her later in this jaunt through
Italy.
I was sitting on the deck of the ship that was to carry Ruth away
from me, looking at the lights out over Dublin Bay, when some one
touched me on the shoulder, and, on turning around, there stood
dear Miss B., who was with us for a time at Killarney. I met her
father on the street the other day, and told him of Ruth's intended
departure. They were very good to come to us that night, and I shall
never forget their kindness in helping me over these first days
without my blessed Ruth. Through them I have made some
charming friends who occupy the time before I start in to study.
Dublin has more pleasure resorts at her door than any other city
in the world. We drove out through Phœnix Park, passing the
summer home of the Lord Lieutenant of Ireland. We made our first
stop at Killiney Castle to get the fine view of Dublin Bay. It was from
this spot that the poet wrote:
"An' I," replied the other, "am afther being over to Kilmary."
Will you believe me when I tell you that nowhere in Europe have
I seen more lovely or better dressed women than right here on
Sackville Street? I have accounted for it, in some degree, by the fact
that our Irish cousins follow the American styles more closely than
do any of their immediate sisters. The Irish woman is always in good
form. One never sees her wearing any sort of jewelry before
luncheon. She is usually found in the morning in a short, tailored
skirt, a chic blouse and hat; some dainty confection of lace and
muslin in the afternoon; and, almost without exception, the middle
class, as well as the gentry, "dress" for dinner; then it is one sees
the beautiful jewels handed down by their forebears.
The first day I was shown over Dublin my guide, in pointing out
the college, said: "This is the Library, and an institute for learning." I
asked, "How far does the Library extend?" meaning, which was the
Library and which the Institute. The honest, but thick-headed, paddy
replied, "To the roof, mum."
SORRENTO:
I was glad when the time came to end traveling and to begin
study; and now I am glad that I can cease my studies and again
begin sight-seeing.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
ebookbell.com