I’m pleased to introduce today’s guest blogger, Nausheen Moulana. Nausheen manages the teams responsible for the design and
development of the MATLAB language. She shares her thoughts on when you might want to create classes in MATLAB.
The thing I like most about the MATLAB environment is the flexibility I have as a programmer to choose the function/API that
I think is required for the task at hand. And what's neat is that if I don't find or like what comes "in-the-box", I can
create my own.
The enhanced object-oriented programming capabilities in the R2008a release of MATLAB add some new tools to our programming toolbox. While I can still program with existing tools such as functions and scripts,
here are some situations where creating a class makes good design sense.
MATLAB, like most programming languages, has a set of primitive data types with a set of operations defined on them. However,
there are situations when we may need to create our own data type. For example, I might want to use structure arrays to track
employee information but want to restrict the addition of new fields or modification of the values associated with existing
employee.age = 23; employee.name = 'Jane'; employee.ID = 17; employee(2) = struct('age',39,'name','Jerry','ID',45); employee
employee = 1x2 struct array with fields: age name ID
The problem I face is that the fields of structure arrays can be modified easily by assigning new values to them just like
I can modify any variables that store primitive data types.
On the other hand, if the variable employee is an object, only functions I choose (as creator of the class) can modify the fields.
The ability to control access and modification of data is referred to as encapsulation. Designing a class facilitates encapsulation thereby improving the quality of my code since objects are robust to accidental
At this point, I'd like to clarify the distinction between classes and objects. Classes are a mechanism to describe interfaces
to the functionality with which users will interact whereas objects are concrete instances of a class with their own data
and related operations. Classes are designed and objects are used.
Another reason I may want to create a new type is to extend or redefine operations on an existing type. For example, I may require integer arithmetic to wrap as opposed to saturate (which is what
MATLAB does) on overflow. I may, in addition, require a sqrt function that works on integers which isn't implemented in MATLAB. I can address these requirements by subclassing from the appropriate integer class in MATLAB and overwriting the arithmetic operations such as +, -, .*, ./, .\ and .^ to wrap on overflow. I can also add a method to my new integer class that computes the sqrt for integer values. Subclassing facilitates code reuse thereby eliminating the need to create new capabilities from scratch.
NOTE: If you do choose to override an arithmetic operator like plus, be aware that you may have to overload other functions that may use plus to ensure they give the right answer.
Using MATLAB's external interface APIs and interoperability capabilities, I can connect to external systems be they external devices such as data acquisition tools or external libraries created using Java or Component Object Model(COM).
A convenient way to interact with these systems is to design a class that manages data access and modification as well as
provides sufficient control over the functionality in the external system that I'd like to expose in MATLAB. By designing
a class, I will be able to add new behaviors as the libraries I interface with evolve without compromising compatibility.
Also, if the external system is implicitly object-oriented then designing a class is the more natural way to present it in
An example in MATLAB of a class which interfaces with an external library is the timer functionality which uses Java's timer object (java.util.Timer).
% Create a timer object and set its % execution mode to schedule timer events. t = timer('TimerFcn','figure;imagesc(magic(5))','Period',1); t.ExecutionMode = 'fixedrate'; % Set name of the timer t.Name = 'MyTimer'; % Set the number of times to execute the callback function. % In this example, the image of magic squares is drawn twice, % once for each of the two events. t.TasksToExecute = 2; % Start the timer. start(t) % Stop and release the timer. stop(t) delete(t)
In this example, designing a class allowed me to reuse timer functionality available in Java while giving me the flexibility to present APIs in a manner that is familiar to users
interacting with objects in MATLAB.
Note that when using new classes written in MATLAB 7.6, I don't need to explicitly call the delete method to remove an object from memory; MATLAB does this automatically when the object is no longer used. The ability for
an object to clean up, via the destructor, when MATLAB determines that the object is no longer being used is just one of the many enhancements
to the object-oriented capabilities in MATLAB 7.6.
Generally MATLAB takes care of managing memory for me. For example, create a 50x50 matrix of doubles.
a = rand(50); a = 5;
With the second assignment to a, MATLAB takes care of freeing the memory allocated in the previous statement without any user intervention. Whenever variables
go out of scope, are modified, or are no longer used, MATLAB automatically releases the memory associated with these variables
when these variables happen to be primitive types. However, if the variables are resources such as file handles, fonts, or
represent other types, then MATLAB needs to transfer control to that object to release resources when the object is no longer
In some situations I may need to take additional action to explicitly manage the lifecycle of the variables that get created. By creating class destructors (the delete method), I can ensure that memory associated with a variable is freed up when the variable is no longer being used. For
example, let's look at the memmapfile class in MATLAB. The memmapfile functionality creates an object that lets me map a file to memory whereby any operations that modify the object in memory
have the effect of modifying the contents of the file on disk.
Here's how I can map a file named records.dat to a series of unsigned 32-bit integers and set every other value to zero via the data property in memory.
m = memmapfile('records.dat', 'format', 'uint32', ... 'writable', true); m.data(1:2:end) = 0;
Since MATLAB does not explicitly allocate the memory for the data contained in the variable m, it cannot release the memory either (i.e., in this case, unmapping the mapped region in MATLAB's memory) when the memmapfile object goes out of scope or is modified via assignment, perhaps in a situation like this.
m = rand(4);
If I exposed the memory mapping functionality directly, I would risk inadvertent memory abuse if users of this class do not
programmatically unmap mapped regions. However, an object-oriented approach mitigates this situation since it provides the
class control over the creation and destruction of objects.
Keywords in MATLAB 7.6 allow me to define my class and organize my code in a single M-file. By having properties, methods, and events defined in the same file, I can gain an insight into class data and operations relatively quickly. With methods, I also
have the flexibility of separating the function definition from implementation. I do so by defining the methods in the file
containing the class definition and implementing the methods in separate files. Depending on the number of methods my class
has, keeping method implementation in separate files can reduce clutter in the class definition.
MATLAB 7.6 has significant enhancements to object-oriented capabilities that simplify the process of designing classes while
providing sufficient functionality to handle your most complex class design. When programming, if you find yourself needing
to do any one of the above, then you should consider designing a class. I'd love to hear when you've found creating classes
to be useful. Let me know here.
Published with MATLAB® 7.6