4
Introduction to Object-Oriented Programming in MATLAB By Stuart McGarrity OBJECT-ORIENTED PROGRAMMING (00) APPLIES TO SOFTWARE DEVELOPMENT the standard science and engineering practice of identifying patterns and de- fining a classification system describing those patterns. Classification systems and design patterns enable engineers and scientists to make sense of complex systems and to reuse efforts by others. By applying classification systems and design patterns to programming, the 00 approach improves your ability to manage software complexity-particularly important when developing and maintaining large applications and data structures. ThiS article demonstrates the use of object-oriented techniques in the MATLAB language to implement a typical technical application. The examples use features avail- able in MATLAB 7.6, part of Release 2008a. 16 sensor array with 2 sources o Sensors - - - Direction of Array -- Direction of Source Application Example: Analyzing Sensor Array Data A sensor array (Figure 1) is a collection of sensors, often arranged in a line, that is used to sample a medium such as air, water, or the ground for radar, sonar, cellular communi- cations, and other applications. By collecting time samples from multiple points in space, you can extract additional information from the medium being sampled. Our application uses a sensor array to determine the direction of arrival (DOA) of multiple distant electromagnetic sources, such as radio beacons and radar transmit- ters. In this particular scenario, we will 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Sensor spacing is 0.125 m FIG URE 1. A sensor array detecting two distant electromagnetic sources at unknown angles. 12 TheMathWorks News&Notes I 2008

Introduction to Object-Oriented Programming in MATLABphp.scripts.psu.edu/users/f/0/f0o/articles/introduction_oop_matlab.pdf · Introduction to Object-Oriented Programming in MATLAB

Embed Size (px)

Citation preview

Introduction to Object-OrientedProgramming in MATLABBy Stuart McGarrity

OBJECT-ORIENTED PROGRAMMING (00) APPLIES TO SOFTWARE DEVELOPMENT

the standard science and engineering practice of identifying patterns and de-

fining a classification system describing those patterns. Classification systems

and design patterns enable engineers and scientists to make sense of complex

systems and to reuse efforts by others. By applying classification systems and

design patterns to programming, the 00 approach improves your ability to

manage software complexity-particularly important when developing and

maintaining large applications and data structures.

ThiS article demonstrates the use of

object-oriented techniques in the MATLABlanguage to implement a typical technical

application. The examples use features avail-able in MATLAB 7.6, part of Release 2008a.

16 sensor array with 2 sources

o Sensors- - - Direction of Array-- Direction of Source

Application Example:Analyzing Sensor Array DataA sensor array (Figure 1) is a collection of

sensors, often arranged in a line, that is usedto sample a medium such as air, water, or theground for radar, sonar, cellular communi-cations, and other applications. By collectingtime samples from multiple points in space,you can extract additional information from

the medium being sampled.

Our application uses a sensor array todetermine the direction of arrival (DOA)of multiple distant electromagnetic sources,such as radio beacons and radar transmit-ters. In this particular scenario, we will

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16Sensor spacing is 0.125 m

FIG URE 1. A sensor array detecting two distant electromagnetic sources at unknown angles.

12 TheMathWorks News&Notes I 2008

attempt to estimate the angles 91 and 92 ofthe two sources relative to the direction in

which the sensor array is pointing.

Reviewing Data Items and OperationsWe will begin by reviewing the data items torepresent and the operations to implement.

As with most applications, many pieces ofdata must be stored and tracked to perform

the required operations. In our example, weneed to represent the following data:

• Numbers of sensors and samples• Sampled sensor data• Sensor sample rate

• Sensor spacing• Wavelength of distant sources

• Speed of wave• Sensor data set name or descriptionWe will use a simple FFT-based technique

to estimate the DOA of the sources. Thistechnique can be broken down into partsand implemented as a collection of opera-tions. A small number of utility operations

needs to be implemented to help with devel-opment work. For example, we must:

• Create the data set from synthetic dataor acquired live data

• Inspect and modify data-set values andparameters

• Plot the sample data to help with inter-pretation and validation

• Calculate and plot the averaged magni-tude squared of the FFT (periodogram)of the data set

• Find the peaks of the periodogram to es-timate DOA of the sources

We can now determine what to representwith class properties and what to implementwith class methods.

Representing Datawith Class PropertiesWe begin by defining a class to describe thesensor array. This initial representation con-

tains only the data items, representing themas class properties.

You define a class in MATLAB with aclass definition file, which contains blocks

of code, denoted by keywords and end state-ments that describe different aspects of theclass. The definition file shown in Figure 2

describes a class sads (for sensor array dataset), with all the data items that we need torepresent listed in a properties block.

Creating an Obiecf and Accessing PropertiesTo create an object or instance of the class

that we defined, we use the statement

»s=sads;To set the value of a property, we specify itsname just like fields of a structure with

»s.NumSensors=16;We can display the object, seeing all theavailable properties and current values, by

typing its name.

»s

s =sadsproperties:

NumSensors: 16NumSamples: []

Data: [)

SampleRate: []

Spacing: []

Wavelength: []

c: 300000000

Name: []

list of methodsAll the properties except NumSensors and

c are still empty. The data set can now be

propertiesWavelengthc""3e8;NumSensorsNwnSamplesDataSpacingSampleRateName

t4J.

121-3

endend

The Language of Object-Oriented Programming

When creating software applications, the

categories you could represent includephysical objects, such as a car or an or-ganism; a virtual entity, such as a financialmarket; or information, such as a set oftest results. In object-oriented program-

ming, these categories are represented asclasses. Data elements, or states, are re-

presented as class properties and opera-tions are implemented as class methods.

An obiect is an instance of a class-

when a program executes, the object iscreated based on its class and behavesin the way defined by the class. The val-

ues stored in MATLABvariables all be-long to a closs. These values include not

only what you might normally considerobjects, such as a time series or state

space object, but also simple doubles.

identified as a sads object using the class and

isa functions and the whos command, some-thing that is not possible with structures.

» class(s)

ans =sads

The ability to identify the class of a vari-

able is important to users who create code to

(just pcoper c re sj

% Wavelength o~ sources (m)~ Speed of wave in medium (m/s)

Number of sensorsNumber of samplesSampled sensor daca

% Spacing of arra7 (m)Sample rate (Hz)

% Sensor array test run n~

FIGURE 2. Class definition file sads. mwith properties.

TheMathWorks News&Notes I 2008 13

operate on the data set, as it lets them deter-mine the available data items to be accessedand operations that can be legally performed.

Error CheckingIf you use structures to represent your data,you could add a new field name at any timesimply by specifying a new field name andassigning it a value. This capability is partic-ularly convenient when you are experiment-

ing with and prototyping algorithms. How-ever, if you misspell a field name, a new fieldwill be added silently, which might cause anerror later that is difficult to diagnose.

Unlike structures, you cannot arbitrarily adda new property to an object simply by specify-

ing a new property name and assigning it avalue. If you misspell an object property name,MATLAB immediately issues an error. This ad-

ditional level of error checking is useful whenthe object is being accessed by users who are lessfamiliar with it than the author, common during

the development of a large application.

Controlling Access to DataClasses give you great control over propertyaccess. For example, they let you prohibitmodification of a property, hide a property,or cause it to be calculated dynamically. You

control access to properties by specifyingproperty attributes in the class definition file.

- c185sc1et sads

:c seeece Arrav Data Set. elas!!propert.ies (Get:A.cce!ls-pr1velCe)

Wavelengeh \ Wavelength ot eour cee (D'l)

end

6

1

8

9lO11213

14~IS'16

171 endIo",!,,< !"---1... _

propert.ies (Co~tanel

c-3e8; \ Speed at wave lin medium (ro/!!)end

properc,1es (Dependene)

NumSensors ~ Number ot sensors

NUlIIS~ple5 'Number o:f oamplesend

propertiesData

SpacinqSampleRaeeNome

% Sampled aenecx data\: Spe.c1nq ot array (1lI)

:c Sewple cece (Hz)

\: Sensor array test run name:

We expand on the class definition file inFigure 2 by dividing the current list of prop-erties into multiple property blocks, each

with unique property attributes: GetAccess,

Constant, and Dependent (Figure 3).You prohibit modification of a property by

setting the Constant attribute, In our exam-ple, we will set the speed of light property c

to be constant. Because constant propertiesdo not change, they can be accessed simply

by referencing the class name.» sads.c _

ans ;

300000000You make a property read-only by setting

the SetAccess attribute to private. You can

make a property visible only to the meth-

ods operating on it by setting the GetAccessattribute to private, as we will do with the

Wavelength property.You can freely change the names or charac-

teristics of a private property without affect-ing users of the object. This "black box" ap-

proach to defining a piece of software, knownas encapsulation, prevents the user of the ob-

ject from becoming dependent on an imple-mentation detail or characteristic that couldchange and break their code.

You specify that a property is calculated

only when asked for by setting its Dependent

attribute.

Isods

FIGURE 3, Class definition file sads. mwith property attributes.

14 TheMathWorks News&Notes I 2008

You then specify a get method that is auto-matically called when the property is accessed.See the "Accessing Properties with Get and SetMethods" section of this article for details on

how to specify class methods. In our applica-

tion, we set the NumSensors and NumSamplesproperties to be dependent.

Implementing Operations withClass MethodsMethods, or the operations that can be per-formed on the object, are specified as a listof functions in a methods block. A class can

contain many types of methods, each fulfill-ing a different purpose, each specified dif-ferently. The following section describes anumber of these types of methods,

We will add a methods block to the sads

definition file and add each new method in-side this block (Figure 4).

Specifying a Constructor MethodIn our example, we will specify a constructor

method that lets the user provide parametersto be used in the creation of the object. Theconstructor method often performs data ini-tialization and validation. The object is nowcreated with»s;sads(Data, wavelength,

SampleRate, Spacing, Name) ;

- c la.!lsdet' sa~

% Sell!!liorArra? Data Set Cla~sarcpecc ree (GeeAccess=privace) []

properties (Constant.) Dproperties (DependenclQpropert.ie~Dmet.hods

tunct.1on obj=sads (Data~ Wavelength,S8l'QpleRate,5pacing~N~) 0.function plot (obj) 0funct ion [mags, t.f.lip]-me.gt:t.t (obj, 2eroPadTo)D:function magttcploC,(obj, zeroPadTo) 0funct.ion angles-doe. (obj) 0:t:unccion NumSensors-qet .NumSe:n:mrs (obj) 0function NumSamp les-oet. NumSamples (obj) 0

end

,.j

lend

FIGURE 4. Class definition file sads . m with methods, displayed in the MATLABeditor. For ease of viewing, the code-foldingfeature is used to hide much of the code.

Implementing Application-Specific MethodsWe will add several methods to implementapplication-specific operations to be per-formed on the data set. Most methods take

the object as an input argument (for exam-

ple, obj) and access the object propertiesby referencing this variable (for example,obj .NurnSarnples), as in this method:function [rnags,fflipl=rnagfft(obj, zpt)

rnag=zeros(obj.NurnSarnples, zpt);

endAlthough it requires additional syntax,

referencing properties via the object variablecan help differentiate them from local func-tion variables, like mag above.

Calling MethodsMethods are called just like functions, with the

object(s) passed in as one of the arguments. Wecall the method that performs the main op-

eration of estimating the sources' DOA.»angles=doa(s)

angles =-10.1642 18.9953

The DOA angles approximate the truelocations of the sources shown in Figure 1,which are -10° and 20°.

Accessing Properties with Get and Set MethodsYou can validate properties or implementdependent properties, as mentioned earlier, .by specifying associated set and get meth-ods. Here is the get method for the NurnSen-

sors property.function NurnSensors=get.NurnSensors(obj)

NumSensors=size(obj.Data,2) ;

endGet and set methods are called automati-

cally when properties are accessed, for ex-ample with»N;s.NumSensorSi

Specifying Methods for Existing MATLABFunctions with OverloadingOverloading lets you redefine existing MATLAB

functions to work on your object by provid-ing a function with that name in your list of

Sensor Array Amplitudes

Q) 2'0;§ 0a.

~ -216

FIGURE 5. Overloaded plot method specializedfor the sensor array data set.

methods. You can also overload operatorsand even indexing by using methods withspecial names. In our application we will in-clude an overloaded plot method, providing

a function to visualize the data set that is fa-

miliar to many MATLAB users (Figure 5).»plot(s)

This customized plot method representsthe information in the most appropriate wayfor this data set, annotating it with all avail-

able information. This plot method is ex-ecuted only on objects for which it has been

defined, a much more robust approach thanmanipulating the order of directories in thepath to control which of the multiple func-tions with the same name are called.

Developing the Application FurtherThe class that we created in this example

represents our sensor array data set and pro-vides several operations that we can use toanalyze the data, including the main direc-tion-finding operation. We can use this class

to evaluate the performance of the FFT-

based technique in different scenarios.We could expand the application using

additional 00 techniques. For example,we could do the following:

• Define subclasses of existing classes (re-

using a definition of a broader categoryto define a more specific subcategory)with inheritance

• Specify static methods, letting us define

an operation for the class as a whole

• Use handle classes with reference behav-ior, enabling us to make data structureslike linked lists or work with a large dataset without copying it

• Define events and listeners, letting usmonitor object properties or actions

These techniques enhance our ability tomanage complexity by enabling us to furtherdefine relationships and behavior in the ap-plication ..

Because it was built using 00 techniques,the application is now robust enough for

others to use and maintain and can be inte-grated with related applications throughoutan organization .•

"'! Resources

OBJECT-ORIENTED PROGRAMMING RESOURCESwww.mathwarks.cam/nn8/aap

TheMathWorksNews&Notes 12008 15