Object Oriented Programming in MATLAB

This post is a summary on object oriented programming (OOP) using MATLAB. It is also a short tutorial that will help you getting started using the OOP features in MATLAB.  Advanced MATLAB users may also find it interesting. Using OOP will make your MATLAB code more readable, easy to maintain and update.

Classes, Methods and Objects in MATLAB

What are objects and why not just use struct?

Objects are instances of a class that have properties and methods to operate on them. Classes give data an identity and associate functions to that identity.

struct objects have field-names, but there are some issues: there is no control over assignment (or access) in struct objects. As an example, if a user spells the field-name incorrectly outside the struct definition, MATLAB will add a new field to the struct. It is also possible to assign the wrong data type to any field-name of a struct.

classdef File

Following is a simple example of a class file.

classdef myclass
 properties
  Name
  Category='Demo'
  ID
 end
end

Unlike struct no new properties can be added by the user of the class (no spelling errors problems)! But access to properties is not yet controlled i.e. a user can set value of Name to double.

Properties Access Rights

There are three levels of property access: private , protected , and public. The access control applies separately to read and write access. Private properties are only accessible from methods of the class. Public properties are accessible anywhere. Protected properties are private properties that are also accessible from subclasses. We will discuss subclasses and Inheritance later in this post. Unless specified explicitly, the properties are public by default. The following examples shows how to assign the access rights to a group of properties.

   properties(GetAccess = 'public', SetAccess = 'private')
       % public read access, but private write access.
   end

   properties(GetAccess = 'private', SetAccess = 'private')
       % private read and write access
   end

Set and Get Methods

The assignment of a value to a property of an instance of a class can be done as follow

object.PropName=RHexpression

Moreover, the programmer can control the access to a property by creating a set.PropName method. Following is an example of defining and calling Property-set methods.

classdef myClass
 properties
  prop1=0;
 end
 methods
  function obj=set.prop1(obj,Value)
   if true %replace true it by any condition
    obj.prop1=Value
   end
  end
 end
end

The set.PropertyName methods are called using the normal (.) syntax in the user code.

a=myClass;
a.prop1=7 % effectively "calls" a=set.prop1(a,7)

As well, the programmer can control the get access to a method by defining a get.PropName method. It is applicable to expressions where object.PropName appears on the right-hand side of an assignment, for example

 A=myfunction(object.PropName,OtherArguments)

The Constructor Method

A constructor method is a method that has the same name as the class name. A user will construct instances of the class (i.e. objects) by calling the constructor. Here is an example of defining a class with a constructor.

classdef myclass
 properties (SetAccess=private)
  prop1=0
 end
 methods
  function obj=myclass(a,b,c)
   %Definition of the constructor method goes here
   obj.prop1=a;
  end
 end
end

Also the definition of the constructor can be as simple as the following

function obj = mydate()
      obj;
end

Operators Overloading

It is convenient to overload commonly used functions to work with objects of your class. In this example, the MyData class overrides the bar function.

classdef MyData
   properties
      Data
   end
   methods
      function obj = MyData(d)
      %This is a constructor method
         if nargin > 0
            obj.Data = d;
         end
      end
      function bar(obj)
      %This methods overloads the bar operator in MATLAB
         y = obj.Data;
         bar(y,'EdgeColor','r');
      end
   end
end

Inheritance

Inheritance in OOP allows us to write subclasses that inherit all of the properties and methods of their superclass so that we do not have to recode all of the parent functionality. The subclass then extends or specializes this functionality.
We can specify a superclass for a class by using the following syntax.

classdef classname < superclass

Also a class might inherit multiple superclasses as follow.

classdef classname < super1 & super2 & super3

At this moment, you can easily guess how to create a subclass alias for an existing class. You just need to inherit the existing class with a different name.

Private Methods

Methods, just like properties, can be private, protected, or public by default. We use private methods to prevent those methods of being accessed directly outside the class interface. The following example illustrates how to define a block of private methods.

 methods(Access = private)
    function sec = calcSecs(obj)
      sec = obj.minute*60 + obj.hour*60*60 + obj.day*24*60*60;
    end

    function TF = isValid(obj)
        TF = obj.minute >= 0 && obj.minute <= 60;
    end
 end

Static Methods

Static methods are methods that do not use any of the properties or other methods of the class. You might need to use static methods in a class to define methods that are thematically related to the class. Those methods are not related to any instance of the class. The definition of a static method in MATLAB can be done as follow.

 methods(Static = true)
     function printCurrentDate()
         display(datestr(now));
     end
 end

To call a static method, you specify the classname (not an instance of the class), followed by a dot and the static method name. We call the previously defined static method as follow.

mydate.printCurrentDate()

Sealed Classes, Methods and Properties

A sealed class cannot be subclassed. Sealed methods and properties cannot be redefined in a subclass i.e. attempting to define a method or property with the same name in a subclass causes an error. The syntax to define respectively a sealed class, method and property is the following:

classdef(Sealed = true) myclass
methods(Sealed = true)
properties(Sealed = true)

Abstract Classes, Methods and Properties

The purpose of abstract properties and abstract methods is to allow the creation of interfaces: the basic idea of an interface class is to specify the properties and methods that each subclass must implement without defining the actual implementation. For example, you can define an abstract superclass  Car with the following definition.

classdef (Abstract) Car
    properties(Abstract) % Initialization is not allowed
      model
      manufacturer
    end
end

Making the properties abstract forces any subclass that inherits the superclass Car to define the properties model and manufacturer.

classdef MyCar < Car
    properties
      model = 'T'
      manufacturer = 'Ford'
    end
end

This explanation applies also to abstract methods. Lets suppose we have a shape superclass with many subclasses like sphere, cube, elipsoid, pyramid, etc. We want every subclass to have a calculateVolume() method. The syntax to define a block of abstract methods is the following:

methods(Abstract = true)
   function vol = calculateVolume(obj,units);
end

Object Arrays

You might need to create array of objects in your MATLAB code. A class constructor can create an array by building the array and returning it as the output argument. For example, the ObjectArray class creates an object array that has the same size as the input array. Then it initializes the Value property of each object to the corresponding input array value.

classdef objectArray
   properties
      Value
   end
   methods
      %Constructor
      function obj = objectArray(F)
         if nargin ~= 0
            m = size(F,1);
            n = size(F,2);
            obj(m,n) = objectArray;
            for i = 1:m
               for j = 1:n
                  obj(i,j).Value = F(i,j);
               end
            end
         end
      end
   end
end

When initializing an object array, it is recommended to pre-allocate the object array by assigning the last element of the array first. Here is an example:

F=zeros(1,5);
Relay=objectArray(F);
    %faster MATLAB processing because the objectArray is pre-allocated
for n=5:-1:1
    %Relay is an array of type relay
    Relay(n)=relay(n);
end

Handle and Value Classes

A value class constructor returns an instance that is associated with the variable to which it is assigned. If you reassign this variable, MATLAB creates a copy of the original object. If you pass this variable to a function, the function must return the modified object.
A handle class constructor returns a handle object that is a reference to the object created. You can assign the handle object to multiple variables or pass it to functions without causing MATLAB to make a copy of the original object. A function that modifies a handle object passed as an input argument does not need to return the object.
All classes that are not subclasses of the handle class are by default value classes. To create handle classes you should inherit the handle class explicitly as in the following example.

classdef MyHandleClass < handle
   ...
end 

Use handle classes if you are creating an object that creates a reference to the data contained in the object. When working with handle classes copying the object does not make copies of the object data.

The best way to practice object oriented programming in MATLAB is to write your own code using the tools presented above. Feel free to revisit this post while developing your MATLAB code and have fun coding your simulations!

Summary
Object Oriented Programming in MATLAB
Article Name
Object Oriented Programming in MATLAB
Description
This post is a summary on object oriented programming (OOP) using MATLAB. It is also a short tutorial that will help you getting started using the OOP features in MATLAB. Advanced MATLAB users may also find it interesting.
Author
Alaa Khreis

Leave a Reply