In this long overdue post, I help you get started with Object Oriented Programming (OOP) in Matlab. We start with a little bit of history of OOP, talk about why and when this is useful and turn to few Matlab examples for you to get immediately started.
In my field, Object Oriented Programming (OOP) in Matlab is a little bit like Principal Component Analysis (PCA) : everybody have heard about it, few have actually coded some and many are afraid to make a leap of faith. The reason for this is that many Matlabers did not have extensive training in coding. But don’t get it wrong, OOP is fun! It’s such a powerful way to code that once you have learned the basics, you will feel deeply empowered. I am hoping to help you out learn these basics to help raise your coding practice.
But let’s not rush and take our time to set the stage. First, before you get into this, you need to be a serious-enough coder :
- You must have mastered most of my introductory posts on Matlab, especially those on structure and cells.
- You must have been using functions and sub-functions for quite a while. It is important that you understand what is the scope of a sub-function as this concept is deeply rooted in OOP.
Both point 1 and 2 are important. Just as you don’t buy the best musical instruments to begin with, I don’t think using OOP straight away will help you learn the basics of programming in Matlab efficiently.
Let’s assume you have all this knowledge set up, what is OOP all about?
OOP has a long history that takes its roots in the 1950-60. According to wikipedia, many of the concepts inherent to OOP were introduced with a version of Simula, a programming language born in Norway. Later on, these ideas were introduced in C++, a newer version of the C language created at the famous BELL lab (Most people know that’s where the transistor was invented but for the neuroscientists in the audience, remember that fMRI was also invented there). The introduction of C++ (along with other languages variants like Object Pascal) pushed OOP into mainstream programming during the 80-90.
Matlab OOP somehow took a troubled path. Mathworks first implementation of OOP (in Matlab 5.0, year 1996, thanks for one reader for the info). In 2008, Mathworks released a complete new refurbished OOP that was not compatible with the previous syntax. This post will only use the newer syntax. I invite you to consult the documentation of the oldest syntax (which is still working in the latest Matlab to this date) if you are interested in that piece of Matlab history.
Now that you know where it comes from, let’s dive and answer this simple question : What is OOP good for?
In procedural programming (the opposite of OOP), we create 2 things : variables and functions. The game of programming is this flow of variables across functions and sub-functions. When you declare a function, you clearly define its input and output variables.
But let’s think a little bit : wouldn’t it be nice if we could pass around objects that contains BOTH the data and the associated functions? As we discussed many times, avoiding duplication of code is always a good practice. Sometimes in procedural programming, it is difficult to create a programming structure that achieve such a feat. That is where OOP comes to the rescue.
Let’s suppose you buy a can of food at a grocery store. Let’s assume the food in the can is the equivalent to some data that is created in a program. To use that food, to eat it, you need some tools to open the can. These tools are like programming functions that you can apply to the can.
Now we know that we can buy two kinds of can at the store. Some with built-in can openers and some without. In other words, some cans will come with both the data (the food) and the functions (the can opener to access the food). Some will even come with a plastic fork. These more advanced cans (isn’t it a brilliant invention? I always marveled at these cans) are like Object-Oriented Objects.
At this point, you might not see how all this could be useful. Let’s take a very very simple example. You have some data that you want to process. You need multiple processing steps and you want to visualize this data at each step. As a result, you could consider creating an object that stores both the data AND the viewer so that it becomes very easy to plot and nicely avoid duplication of figure creation.
Now that you got the idea, how to get started?
There are several ways to declare objects in Matlab. This is a vast topic so I am going to stick to simple things (for now). You need to create a file that is the same name as your object. Each object will grossly be defined in two parts (again there are more but we will keep it for later) : the properties and the methods.
- The properties are your variables. They stored all the data that is relevant to your object.
- The methods are the functions that are bundled with your object.
Let’s make our first OOP class :
classdef ImageData properties Data; end methods function obj=ImageData(DataToStore) obj.Data=DataToStore; end function View(obj) figure(); imagesc(obj.Data); end end end
classdef is the standard function to declare a class. The name of the class here is “ImageData”. You need to save that class in a file named ImageData.m and have this file in your search path.
Following that, there is a “properties” block that finished with an “end”. You can have as many property block, each one with different options (or attributes). Within that block, you will list all your variables. Here we only have one called “ImgData”.
The next block is a “method” block. There will be your functions or methods of the class. As for the property block, there are attributes you can specify. By far the most important are public vs private which we will discuss in a dedicated post. The code I provide here is only using default values.
There are two function in ImgData :
- The first will probably look weird to you as it is called the same way as the class itself : “ImageData“. This function is very important, it is the constructor of your class. It is invoked every time you create a new instance of that class. Grossly, you can view this as an initialization method. As opposed to some other languages, it is not strictly required in Matlab to define it but highly recommended. I view this as a rule of good coding practice, the same way as you are advised to do memory preallocation of large arrays.
- The second one called “View” is a custom function for this particular class that I defined. It is the method we discussed earlier on that implements the plotting of the data.
Now that you have your first class defined, how to use it?
Well, it is quite easy. You first do :
Here, We call the constructor of the class and pass the argument DataToStore to it (here a random image). D is now an instance of the class. It is important to note that you can have as many instances of that class as you want. They will not share any variables between each other (except for the code implementation) and be fully independent objects.
Then, calling a method of that class is piece of cake :
This will call the “View” method and create the figure window as expected. You can also do :
It is an equivalent syntax (although slightly faster computationally if you have complicated class structures).
Since the property Data is a public property (the default attribute), you can access it from outside the class (ie. the scope is not restricted to the methods of the class). So you can do :
And now, this call will show some new figure with the updated data property :
That’s it for today, you can now shine in cocktail parties with your new OOP skills!