<<

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 16 sensor array with 2 sources language to implement a typical technical o Sensors - - - Direction of Array application. The examples use features avail- -- Direction of Source able in MATLAB 7.6, part of Release 2008a.

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) 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 of multiple distant electromagnetic sources, Sensor spacing is 0.125 m such as radio beacons and radar transmit- ters. In this particular scenario, we will FIG URE 1. A sensor array detecting two distant electromagnetic sources at unknown angles.

12 TheMathWorks News&Notes I 2008 The Language of Object- attempt to estimate the angles 91 and 92 of of code, denoted by keywords and end state- the two sources relative to the direction in ments that describe different aspects of the Oriented Programming which the sensor array is pointing. class. The definition file shown in Figure 2 describes a class sads (for sensor array data When creating software applications, the Reviewing Data Items and Operations set), with all the data items that we need to categories you could represent include We will begin by reviewing the data items to represent listed in a properties block. physical objects, such as a car or an or- represent and the operations to implement. ganism; a virtual entity, such as a financial As with most applications, many pieces of Creating an Obiecf and Accessing Properties market; or information, such as a set of data must be stored and tracked to perform To create an object or instance of the class test results. In object-oriented program- the required operations. In our example, we that we defined, we use the statement ming, these categories are represented as need to represent the following data: »s=sads; classes. Data elements, or states, are re- • Numbers of sensors and samples To set the value of a property, we specify its presented as class properties and opera- • Sampled sensor data name just like fields of a structure with tions are implemented as class methods. • Sensor sample rate »s.NumSensors=16; An obiect is an instance of a class- • Sensor spacing We can display the object, seeing all the when a program executes, the object is • Wavelength of distant sources available properties and current values, by created based on its class and behaves • Speed of wave typing its name. in the way defined by the class. The val- • Sensor data set name or description »s ues stored in MATLABvariables all be- We will use a simple FFT-based technique s = long to a closs. These values include not to estimate the DOA of the sources. This sads only what you might normally consider technique can be broken down into parts properties: objects, such as a time series or state and implemented as a collection of opera- NumSensors: 16 space object, but also simple doubles. tions. A small number of utility operations NumSamples: [] needs to be implemented to help with devel- Data: [) opment work. For example, we must: SampleRate: [] identified as a sads object using the class and • Create the data set from synthetic data Spacing: [] isa functions and the whos command, some- or acquired live data Wavelength: [] thing that is not possible with structures.

• Inspect and modify data-set values and c: 300000000 » class(s) parameters Name: [] ans = • Plot the sample data to help with inter- list of methods sads pretation and validation All the properties except NumSensors and The ability to identify the class of a vari- • Calculate and plot the averaged magni- c are still empty. The data set can now be able is important to users who create code to 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 represent with class properties and what to implement (just pcoper c re sj with class methods. properties Wavelength % Wavelength o~ sources (m) c""3e8; ~ Speed of wave in medium (m/s) Representing Data NumSensors Number of sensors NwnSamples Number of samples with Class Properties Data Sampled sensor daca We begin by defining a class to describe the Spacing % Spacing of arra7 (m) t4 SampleRate Sample rate (Hz) sensor array. This initial representation con- J. Name % Sensor array test run n~ tains only the data items, representing them 12 end 1-3 end as class properties. You define a class in MATLAB with a class definition file, which contains blocks FIGURE 2. Class definition file sads. mwith properties.

TheMathWorks News&Notes I 2008 13 operate on the data set, as it lets them deter- We expand on the class definition file in You then specify a get method that is auto- mine the available data items to be accessed Figure 2 by dividing the current list of prop- matically called when the property is accessed. and operations that can be legally performed. erties into multiple property blocks, each See the "Accessing Properties with Get and Set with unique property attributes: GetAccess, Methods" section of this article for details on Error Checking Constant, and Dependent (Figure 3). how to specify class methods. In our applica- If you use structures to represent your data, You prohibit modification of a property by tion, we set the NumSensors and NumSamples you could add a new field name at any time setting the Constant attribute, In our exam- properties to be dependent. simply by specifying a new field name and ple, we will set the speed of light property c assigning it a value. This capability is partic- to be constant. Because constant properties Implementing Operations with ularly convenient when you are experiment- do not change, they can be accessed simply Class Methods ing with and prototyping algorithms. How- by referencing the class name. Methods, or the operations that can be per- ever, if you misspell a field name, a new field » sads.c _ formed on the object, are specified as a list will be added silently, which might cause an ans ; of functions in a methods block. A class can

error later that is difficult to diagnose. 300000000 contain many types of methods, each fulfill- Unlike structures, you cannot arbitrarily add You make a property read-only by setting ing a different purpose, each specified dif- a new property to an object simply by specify- the SetAccess attribute to private. You can ferently. The following section describes a ing a new property name and assigning it a make a property visible only to the meth- number of these types of methods, value. If you misspell an object property name, ods operating on it by setting the GetAccess We will add a methods block to the sads MATLAB immediately issues an error. This ad- attribute to private, as we will do with the definition file and add each new method in- ditional level of error checking is useful when Wavelength property. side this block (Figure 4). the object is being accessed by users who are less You can freely change the names or charac- familiar with it than the author, common during teristics of a private property without affect- Specifying a Constructor Method the development of a large application. ing users of the object. This "black box" ap- In our example, we will specify a constructor proach to defining a piece of software, known method that lets the user provide parameters Controlling Access to Data as encapsulation, prevents the user of the ob- to be used in the creation of the object. The Classes give you great control over property ject from becoming dependent on an imple- constructor method often performs data ini- access. For example, they let you prohibit mentation detail or characteristic that could tialization and validation. The object is now modification of a property, hide a property, change and break their code. created with or cause it to be calculated dynamically. You You specify that a property is calculated »s;sads(Data, wavelength, control access to properties by specifying only when asked for by setting its Dependent SampleRate, Spacing, Name); property attributes in the class definition file. attribute.

- c185sc1et sads - c la.!lsdet' sa~ :c seeece Arrav Data Set. elas!! % Sell!!liorArra? Data Set Cla~s propert.ies (Get:A.cce!ls-pr1velCe) arcpecc re e (GeeAccess=privace) [] Wavelengeh \ Wavelength ot eour cee ('l) properties (Constant.) D end properties (DependenclQ 6 propert.ies (Co~tanel ,. propert.ie~D 1 c-3e8; \ Speed at wave lin medium (ro/!!) j met.hods 8 end tunct.1on obj=sads (Data~ Wavelength,S8l'QpleRate,5pacing~N~) 0 9 properc,1es (Dependene) .function plot (obj) 0 lO NumSensors ~ Number ot sensors funct ion [mags, t.f.lip]-me.gt:t.t (obj, 2eroPadTo) D 1 NUlIIS~ple5 'Number o:f oamples l :function magttcploC,(obj, zeroPadTo) 0 12 end funct.ion angles-doe. (obj) 13 properties 0 :t:unccion NumSensors-qet .NumSe:n:mrs (obj) 14~ Data % Sampled aenecx data 0 function NumSamp les-oet. NumSamples (obj) IS' Spacinq \: Spe.c1nq ot array (1lI) 0 16 SampleRaee :c Sewple cece (Hz) end 17 Nome \: Sensor array test run name: end Io",!,,< 1!"---1... end _

Isods FIGURE 4. Class definition file sads . mwith methods, displayed in the MATLAB FIGURE 3, Class definition file sads. mwith property attributes. editor. For ease of viewing, the code-foldingfeature is used to hide much of the code.

14 TheMathWorks News&Notes I 2008 Implementing Application-Specific Methods Sensor Array Amplitudes We will add several methods to implement application-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 properties by referencing this variable (for example, obj .NurnSarnples), as in this method:

Q) 2 function [rnags,fflipl=rnagfft(obj, zpt) '0 ;§ 0 rnag=zeros(obj.NurnSarnples, zpt); a. ~ -2 16 end Although it requires additional syntax, referencing properties via the object variable can help differentiate them from local func- tion variables, like mag above.

Calling Methods FIGURE 5. Overloaded plot method specializedfor the sensor array data set. Methods are called just like functions, with the object(s) passed in as one of the arguments. We methods. You can also overload operators using a definition of a broader category call the method that performs the main op- and even indexing by using methods with to define a more specific subcategory) eration of estimating the sources' DOA. special names. In our application we will in- with inheritance »angles=doa(s) clude an overloaded plot method, providing • Specify static methods, letting us define angles = a function to visualize the data set that is fa- an operation for the class as a whole

-10.1642 18.9953 miliar to many MATLAB users (Figure 5). • Use handle classes with reference behav- The DOA angles approximate the true »plot(s) ior, enabling us to make data structures locations of the sources shown in Figure 1, This customized plot method represents like linked lists or work with a large data which are -10° and 20°. the information in the most appropriate way set without copying it for this data set, annotating it with all avail- • Define events and listeners, letting us Accessing Properties with Get and Set Methods able information. This plot method is ex- monitor object properties or actions You can validate properties or implement ecuted only on objects for which it has been These techniques enhance our ability to dependent properties, as mentioned earlier, . defined, a much more robust approach than manage complexity by enabling us to further by specifying associated set and get meth- manipulating the order of directories in the define relationships and behavior in the ap- ods. Here is the get method for the NurnSen- path to control which of the multiple func- plication .. sors property. tions with the same name are called. Because it was built using 00 techniques, function NurnSensors=get.NurnSensors(obj) the application is now robust enough for NumSensors=size(obj.Data,2) ; Developing the Application Further others to use and maintain and can be inte- end The class that we created in this example grated with related applications throughout Get and set methods are called automati- represents our sensor array data set and pro- an organization .• cally when properties are accessed, for ex- vides several operations that we can use to ample with analyze the data, including the main direc- »N;s.NumSensorSi tion-finding operation. We can use this class to evaluate the performance of the FFT- Specifying Methods for Existing MATLAB based technique in different scenarios. "'! Resources Functions with Overloading We could expand the application using

Overloading lets you redefine existing MATLAB additional 00 techniques. For example, OBJECT-ORIENTED PROGRAMMING RESOURCES www.mathwarks.cam/nn8/aap functions to work on your object by provid- we could do the following: ing a function with that name in your list of • Define subclasses of existing classes (re-

TheMathWorksNews&Notes 12008 15