What is the use of matlab

Introduction to object-oriented programming with MATLAB

By Stuart McGarrity and Adam Sifounakis, MathWorks

When creating software applications, it is important to organize the various building blocks of your software into related groups. For example, a custom numeric solver may require multiple configuration parameters and routines to perform a full set of calculations. Object oriented programming (OOP) allows you to define the configuration parameters (properties) of the solver with its functions (methods) in a single definition or class to group. Everything a user needs to run this solver correctly is defined in this class.

An object is an instance of a class. When a program is run, the object is created based on its class definition, and it behaves as it was defined by the class. The properties of an object represent its state and its methods represent all actions that a user can take. In this way, a code author can easily group all related data and functions for a software system, and a user can easily find and use all the functionalities that the code author has developed.

The following example uses object-oriented programming to create an application that analyzes sensor data from a sensor array.

Application example: Analyzing sensor array data

A sensor array (Figure 1) is a collection of sensors that are often arranged in a row and used to collect data from a medium such as air, water or ground for radar, sonar or cellular communications. By collecting data from multiple points in space, one can extract additional information from the appropriate medium.

Figure 1. A sensor array that detects two distant electromagnetic sources at unknown angles.

Our application uses a sensor array to determine the direction of arrival (AR) of several distant electromagnetic sources, such as B. Beacons and radar transmitters. In this scenario we will try to estimate the angles θ1 and θ2 of the two sources relative to the direction the sensor array is pointing.

Examination of the available data and operations

For this application we need to save and display the following data:

  • Number of sensors and data points
  • Scanned sensor data
  • Sensor sampling rate
  • Distance between the sensors
  • Wavelength of distant sources
  • Speed ​​of the wave
  • Name or description of the sensor data set

We will use a simple technique based on Fast Fourier Transform (FFT) to estimate the AR of the sources. This technique can be broken down into sub-steps and implemented as a collection of operations. To simplify the development work, a small number of auxiliary functions are implemented. So we have to z. B. Do the following:

  • Build the dataset from synthetic data or captured live data
  • Check and change data record values ​​and parameters
  • Graph the data set to aid interpretation and validation
  • Calculate and record the power density spectrum of the data set (using a simple square of the FFT method)
  • Find the peaks in the power density spectrum to estimate the direction of arrival of the sources

Now that we have identified the data we need to represent and the activities we need to perform, we can represent the data with class properties and the activities with class methods.

Representation of data with class properties

We start by defining a class to describe the sensor array. This initial representation only contains the data elements and presents them as class properties.

With a class definition file you define a class in MATLAB®that begins with the keyword and ends with the keyword. Within the class definition block, additional keyword blocks describe various aspects of the class, such as: B. Class properties and class methods. The definition file shown in Figure 2 describes a class (sensor array data set) with all data elements that we need to represent, listed in a property block.

Figure 2. Class definition file with properties.

Create an object and access properties

To create an object or an instance of the class we have defined, we use the instruction

>> s = sads;

To determine the value of a property, we name its name just like fields in a structure

>> s.NumSensors = 16;

We can view the object and see all the available properties and current values ​​by typing its name.

>> s s = sads with properties: Wavelength: [] c: 300000000 NumSensors: 16 NumSamples: [] Data: [] Spacing: [] SampleRate: [] Name: []

All properties except and are still empty. The data record can now be identified as an object using the function, the function and the command, which is not possible with structures.

>> class (s) ans = 'sads'

The ability to identify the class of a variable is important for users writing code to manipulate the record, as it allows them to determine the available data items that can be accessed and the operations that can be performed.

If you use structures to represent your data, you can always add a new field by simply specifying a new field name and assigning it a value. This is especially useful when you are experimenting with algorithms and building prototypes. However, if you misspell a field name, a new field is silently added, which can later lead to a difficult-to-diagnose error.

Unlike structures, you cannot dynamically add a new property to an object simply by specifying a new property name and assigning it a value. If you misspell the name of an object property, MATLAB immediately returns an error message. This additional level of error checking is useful when the object is accessed by users who are less familiar with the object than the author, which is often the case when developing a large application.

Control access to data

Classes give you a great deal of control over how properties are accessed. For example, you can prohibit the modification of a property, hide a property or have it calculated dynamically. You control access to properties by specifying property attributes in the class definition file. We extend the class definition file in Figure 2 by dividing the current list of properties into several property blocks, each with unique property attributes:, and (Figure 3).

Figure 3. Class definition file with property attributes.

You prevent a property from being changed by specifying the attribute. In our example we set the speed of light property to be constant. Since constant properties do not change, they can be accessed simply by referencing the class name.

>> sads.c ans = 300000000

You make a property read-only by setting the attribute to. You can make a property visible only to the methods that are working with it by setting the attribute to, just as we are going to do with the property.

You can change the names or characteristics of a property marked with the keyword as you wish without affecting the users of the object. This “black box” approach to defining software, known as encapsulation, prevents the user of the object from becoming dependent on an implementation detail or property that might require a change in its code or even make its code inoperable .

You can specify that a property is only calculated when it is requested by setting the attribute.

You then specify a Get method that is called automatically when the property is accessed. For details on defining class methods, see the “Accessing Properties Using Get and Set Methods” section in this article. In our application we define the properties and as.

Implement operations with class methods

Methods or the operations that can be performed on the object are specified as a list of functions in a method block. A class can contain many types of methods, each with a different purpose and specified differently. The following section describes a number of these types of methods.

We will add the methods block to the definition file and insert each new method into this block (Figure 4).

Figure 4. Class definition file with methods displayed in the MATLAB editor. To make the display easier, the code collapse function is used to hide a large part of the code.

Specify a constructor method

In our example, we specify a constructor method that allows the user to specify parameters to be used when creating the object. The constructor method often performs data initialization and validation. The object is now created with the command

>> s = sads (Data, Wavelength, SampleRate, Spacing, Name);

Implement application-specific methods

We will add several methods of implementing application specific operations to be performed on the data set. Most methods take the object as an input argument (e.g.) and access the object properties by referencing this variable (e.g.) as in the following method:

function mag = [mags, fflip] = magfft (obj, zpt) mag = zeros (obj.NumSamples, zpt); ... end

Although it requires additional syntax, referencing properties through the object variable can help to identify them from local function variables such as: B. above to distinguish.

Methods are called just like functions, with the passed object being one of the arguments. We can estimate the AR angles of the sources by calling the method of our class.

>> angles = doa (s) angles = -10.1642 18.9953

The AR angles are approximations of the true positions of the sources shown in Figure 1, which are at -10 ° and 20 °.

Accessing properties with get and set methods

You can validate properties or implement dependent properties by specifying associated Set and Get methods. Here is the get method for the property.

function NumSensors = get.NumSensors (obj) NumSensors = size (obj.Data, 2); end

Get and Set methods are called automatically when properties are accessed, for example with

Specifying methods for existing MATLAB functions using overloading

Overloading allows you to redefine existing MATLAB functions for use with your object by providing a function with the same name in your method list. In our application, we will overload the method that provides a function for visualizing the data set that is familiar to many MATLAB users (Figure 5).

>> plot (s)

Figure 5. Overloaded display method specialized for the sensor array data set.

This custom method presents the information in the most appropriate way for that dataset, with the appropriate labels on the axes. It only works on objects for which it has been defined - a much more robust approach than manipulating the order of directories in the path.

If you want special behavior for your class, you can also overload basic operators and even indexing by using methods with special names.

Develop the application further

The class we created in this example represents our sensor array dataset and allows us to easily perform a complex, specialized analysis of our data, including at the heart of it, determining the direction of arrival. With this class, we can quickly assess the accuracy of the FFT-based technique in different scenarios.

We could extend the application with additional OO techniques. For example, we could do the following:

  • Defining subclasses of existing classes (reusing a definition of a broader category to define a more specific subcategory) via inheritance
  • Specification of static methods to define an operation for the class as a whole
  • Use of handle classes with reference behavior that allow us to create data structures such as linked lists or work with a large data set without copying it
  • Define events and listeners to monitor object properties or actions

These techniques improve our ability to deal with complexity by allowing us to further define relationships and behavior in the application.

Because it was built using OO techniques, the application is now robust enough to be used and maintained by others, and it can be integrated with other applications within an organization.

Released 2020

View articles for related industries