Can you transition from MATLAB to Python without classes?

Jozsef Meszaros
7 min readJul 31, 2022

Academic scientists steeped in MATLAB will need to be comfortable with classes to successfully transition to Python

Classes can be useful for trying to educate ourselves— but in computer science, classes are programmatic instructions for simply achieving sophisticated computational objectives in a self-contained way.

When is the last time you sat down to your MATLAB console and typed out something like mydata.myfunction()? Right now you might be saying “That’s not MATLAB”. Especially if, like me, you learned MATLAB because you needed a way to analyze your data (or a collaborator needed a way for you to analyze their data).

Why does mydata.myfunction() look so odd to us?

Because programming with classes and objects is not common for MATLAB users. But if you want to transition from MATLAB to Python, you absolutely need to be familiar with classes and objects.

How do you get started? If you have ever written a MATLAB function, you will be able to write and understand classes.

This post is intended for intermediate-level MATLAB users to get familiar with the vocabulary and implementation of classes and objects, an essential step in transitioning to more industry-oriented tech positions.

Let’s cover three basic concepts and jump into an example:

  • Classes: Basically, a blueprint for a set of functions and a structure that will store data for those functions (stored in MATLAB as a .m file)
  • Objects: Imagine taking a blueprint and turning it into a real thing: an object. But the object goes further than the blueprint: Not only does it have instructions for building the house — but once you built it, it also has instructions for later painting the walls, switching out the carpet, putting up holiday decorations, etc (objects are created in your workspace and each object is treated as its own variable)
  • Methods: A way to execute functions that are specific to your object (methods are written into the class file and used on objects)

Basically, objects are like variables with a limitless repertoire of things they can do to themselves — they store data but they can also alter that data (hence, the methods). Methods are functions specific to your object — defined by the class. Additionally, I will show examples of two other concepts: class instances and overloaded functions (not a bad thing!)

You may already use classes in MATLAB without knowing it

One example of a class that MATLAB users rely on is gmdistribution, a class for creating a Gaussian Mixture distribution.

mygm = gmdistribution([0,10],[1,2])

MATLAB will, rather stoically, return:

Is this the end of the object mygm? Typically, with a function, you enter it and what you get is an output and you move on. But mygm is an object of class gmdistribution and creating it was just the first step.

Like for any object, you can get help by typing: help(mygm). You can also look at the type of class (blueprint) that built the object by typing: class(mygm).

Let’s type your first command using dot notation:

two_random_numbers = mygm.random()

If you were to just type “.random()” on a variable that wasn’t a gmdistribution, you’d get an error:

That’s because methods are specific to classes. Now, let’s explore some properties of mygm. Remember that a class not only has functions (which we refer to as methods) but also information about your data, which we call properties or attributes.

By typing help(mygm) you’ll see a list of properties/attributes.

You can retrieve any of these properties using dot notation. Just type one of them after mygm and a dot — just like you did for the function/method.

mygm.NumVariables
mygm.DistributionName
mygm.mu
mygm.Sigma
%etc...

videoWriter, another example, of a MATLAB class

Ever tried to write a video in MATLAB? It involves VideoWriter, a class.

video1 = VideoWriter(‘myfile.avi’ , ‘MPEG-4’); % House building part

Remember that you can build a green house and then later decide to decorate the walls. Objects can be designed for you to modify their properties even once they’re created! The VideoWriter class enables this.

video1.Quality = 95; % Decorating the walls part
video1.FrameRate = 20;

You’ll next write a single frame to your video:

a = rand(300);
video1.open();
video1.writeVideo(a);
video1.close();

Typically with a function, you call the function and that’s the end of it. With an object, there can be a process with a set of steps that involve setting properties and invoking methods, as we did above with the Quality, FrameRate, and then ultimately, writing the frame. Clearly, objects are more complex than functions alone, but they’re also far more self-contained, logical, and the basis for more advanced programming environments (like Python).

Now let’s write our own custom class

In MATLAB, a class is created using the editor and saved as a “.m” file, just like a function. Copy this one into the MATLAB editor and save it as fileclass.m:

This class will allow you to store information about a file, summarize it, and compare the sizes of files (it won’t modify or do anything to the files themselves).

Constructor method The most important method in any class is the constructor method. Best practice is to have the file name of the class, the classdef and the constructor named the same way. The constructor method can take arguments (in our case, inputfile) or not, just like a typical function.

Now let’s give our example class a test run. Copy and paste the code that applies to you from below. Browse to a directory and take a look at the files located there by doing as follows:

% Windows example
cd('C:\Windows\')
dir('*.exe')
% Mac example
cd('\bin')
dir()

New vocabulary word alert — instance: I’m going to create two instances of our fileclass object by typing the lines below:

% Windows example
file1 = fileclass('writer.exe');
file2 = fileclass('notepad.exe');
% Mac example
file1 = fileclass('bash');
file2 = fileclass('sh');

Try out the method we created called summary. If you aren’t sure how, just glance up at the work we’ve done in this post so far.

The other method of fileclass we wrote is lt, which means “less than”. However, because this is considered a “built-in” function and an operator of MATLAB, the presence of lt in the class is understood as an overloaded function. Why? Because you are creating a unique additional role for a function that already existed! Go ahead and try it:

file1 < file2

This might seem like a trivial use — but imagine a situation where you have created your own class, let’s class it “eventclass” and it defines when an event occurs and what kind of event it was — you can use the same approach taken here to tell you whether one event happened before the other by simply writing event_x<event_y!

You may be wondering how functions differ from methods — and hopefully the above example shows you that methods are far more extensible (a programming term meaning it enables more use cases). For example, you could never write a stand-alone function that is the less than comparator above. There are many other wonderful ways to extend methods for a variety of uses — which is at the core of much programming.

Now how does this help me with Python?

Nearly everything in Python relies on objects and classes. Even a numpy array is an object, which is different from a pandas dataframe object. Which means they have different methods!

Let’s go ahead and reproduce the class we just made in MATLAB, this time in Python. I recommend using Python from within Google Colab for a carefree prototyping experience. Simply type or paste the code below into a Python cell. Execute it.

Can you tell what the constructor function here is? Answer below.

Now, if you are in the Google colab environment, you can browse to the sample data files, otherwise find some files on your local computer:

import os
os.chdir('/content/sample_data')
os.listdir()
# Output ['README.md', 'anscombe.json', 'mnist_train_small.csv', # 'california_housing_train.csv', 'california_housing_test.csv',
# 'mnist_test.csv']

Now in the next cell, try out the summary method. (Hint: This will be done using dot notation!) — then try the less than operator, just like you had in MATLAB. You should see the clear parallels between using classes in MATLAB and Python, and now you are capable of understanding object-oriented programming in both environments!

Answer: The constructor method for a Python class is always “__init__”, short for initialize.

Here is a quick table that you can refer to for remembering how classes, objects, and methods work together.

I hope this post has helped you see how to bridge MATLAB and Python. Hopefully you can simultaneously advance your skills in both to accomplish your objectives.

There’s lots more to learn about classes in both MATLAB and Python, and I’ll be discussing these topics in future posts.

--

--