Why You Should Switch to Python from Matlab
Posted on June 2, 2023 by Zach Strout
Biomechanics researchers and engineers often turn to powerful computational tools to handle, analyze, and visualize intricate data like IMU data or quaternions. Matlab is a popular choice among the various programming languages available, offering a comprehensive Integrated Development Environment (IDE) for writing scripts. For many, including myself, Matlab was what you first learned programming with, making it difficult to transition to other, more capable languages like Python. In this post, we'll guide you through installing Python and an excellent editor complete with plugins to simplify coding in Python. We'll also cover the syntax differences between Matlab and Python for common tasks like reading files or plotting. Finally, we'll present specific reasons to make the switch to Python.
How to get started with Python
While you can download Python and edit your Python scripts in any text editor, the best way to start with Python is to start with the code editor. One of the best code editors out there is VS Code. It is an open-source code editor by Microsoft that includes many useful features such as debugging, syntax highlighting, code completion, and extensions. These extensions can be used to make it function more like a complete IDE like the Matlab code editor.
To get started with VS Code and Python, you can visit the VS Code "Getting Started with Python in VS Code" page While this guide is a great start, here are tips that could help with installation:
When it comes time to install a version of Python, you will be given the option to install many different versions from 3.7 to 3.11. If you plan on using lots of external libraries, you should probably pick something like 3.9 or 3.8. If you don't, you can go ahead and get the latest version.
The tutorial, talks about using virtual environments to install packages. While this is generally good advice, it is not completely necessary. To install new packages, you can simply type the following into the terminal or command prompt:
py -m pip install matplotlib
or
pip install matplotlib
At the bottom of the Getting Started tutorial, feel free to check out the other helpful options such as Debugging or Editing Code.
If you'd like to try out Python in an environment similar to Matlab's Command Window, you can use the Python command-line interface. Depending on your operating system, you can enter 'py' or 'python' to access this interface.
What are the basic syntax differences between Python and Matlab?
There are some basic things that every program does: reading a file, looping through the data, doing basic calculations and using functions, plotting, and writing files.
Here are some quick comparisons.
Read all files in a directory
Matlab
folder_path = '/path/to/your/folder';
file_list = dir(folder_path);
for file_idx = 1:numel(file_list)
file_name = file_list(file_idx).name;
full_file_path = fullfile(folder_path, file_name);
file_content = readtable(full_file_path);
end
Python
import os
import pandas as pd
folder_path = '/path/to/your/folder'
for file_name in os.listdir(folder_path):
full_file_path = os.path.join(folder_path, file_name)
data = pd.read_csv(full_file_path)
Note: this example uses the really powerful Python library called
pandas
to read the csv file into a variable. While Pandas can be a little slow, it is really easy to do calculations with the pandas data structure. For example, if you want to calculate the mean of a column in a csv, you can simply read the csv with data = pd.read_csv(path)
and calculate the mean with data["column_of_interest"].mean()
. There are lower level libraries for reading data that are faster, but pandas is more flexible. As with any other Python library that is not included with the base Python, you can install it with pip install pandas
in the command prompt or terminal.
Looping
Matlab
% While loops
counter = 0;
while counter < 5
disp(counter);
counter = counter + 1;
end
% Basic for loop
for i = 1:5
disp(i);
end
% Iterating over cell array
segments = {'foot', 'shank', 'thigh'};
for idx = 1:length(segments)
segment = segments{idx};
disp(segment);
end
Python
# While loops
counter = 0
while counter < 5:
print(counter)
counter += 1
# Basic iterator loop
# The range function creates an iteration that goes from
# 0 to 4
for i in range(5):
print(i)
# Looping through a list (a list is somewhat like an array)
segments = ['foot', 'shank', 'thigh']
for segment in segments:
print(segment)
Creating and using functions
Matlab
% Function that returns nothing
function greet(name)
fprintf('Hello, %s!\n', name);
end
name = 'John';
greet(name);
% Function that returns one thing
function result = square(x)
result = x * x;
end
number = 5;
result = square(number);
fprintf('The square of %d is %d\n', number, result);
% Function that returns multiple things
function [min_val, max_val] = min_max(numbers)
min_val = min(numbers);
max_val = max(numbers);
end
numbers = [2, 5, 1, 8, 3];
[min_val, max_val] = min_max(numbers);
fprintf('Min value: %d, Max value: %d\n', min_val, max_val);
Python
# Function that returns nothing
def greet(name):
print(f'Hello, {name}!')
name = 'John'
greet(name)
# Function that returns one thing
def square(x):
return x * x
number = 5
result = square(number)
print(f'The square of {number} is {result}')
# Function that returns multiple things
def min_max(numbers):
return min(numbers), max(numbers)
numbers = [2, 5, 1, 8, 3]
min_val, max_val = min_max(numbers)
print(f'Min value: {min_val}, Max value: {max_val}')
Plotting
Matlab
x = linspace(0, 2 * pi, 100);
y = sin(x);
plot(x, y);
xlabel('x');
ylabel('sin(x)');
title('Sine Wave');
grid on;
Python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Sine Wave')
plt.grid(True)
plt.show()
Numpy is a common library for doing calculations with Python. It will let you do typical array type calculations. You can install it with pip install numpy
.
Matplotlib is a common library for plotting in Python. It takes inspiration from Matlab for a lot of the syntax. You can install it with pip install matplotlib
.
What are some reasons to switch from Matlab to Python?
Here are some reasons you may want to add Python to your arsenal of programming languages for research purposes or even to make the plunge to completely switch from Matlab to Python.
Open source
Python is open source and available for free. If you transfer to a university or company without a Matlab licence, you can simply download Python and get working. Beyond the core Python code, many packages such as sklearn which is used for machine learning, Torch or Tensorflow which are used for deep learning, pandas which is a general purpose data analysis library, or other open algorithms are all open source and free too.
Libraries
Python has roughly 10x more libraries than Matlab (Python libraries vs Matlab libraries). One of the benefits of Python is how it interacts with other code through libraries. Because of this, python has been called a "glue language" since it is great for combining different code components through simple, pythonic APIs. As previously mentioned, some common APIs include those for machine learning (Sklearn), deep learning (Torch, Tensorflow, and Keras), those for scientific computing (scipy), those for orientation and attitude estimation (the AHRS package), and numerous other ones.
Documentation and Community
While the Matlab documentation and communuty forums are really good, they do have limits. You can use the documentation to figure out how certain functions work, but when it comes time to combine those functions, the Matlab documentation might be lacking. Since Python is one of the most popular languages and is open source, there are lots of resources online including Stack Overflow and some Medium articles that can help a lot when working with Python. In addition, Large Language Models such as GPT-4 have been trained on lots of Python open source code, so you can for example ask ChatGPT how to do something in a language, how to optimize code, how code works, or even how to convert Matlab code to Python code.
Find Out More
Want to learn more? Check out these other links for Python:
Jupyter is a notebook-based way to program in Python which is a bit closer to programming in Matlab. With Jupyter Notebooks, you can create code cells, run individual cells interactively, and write documentation in Markdown. While you can run Jupyter on your own computer, you can also use Google Colab which allows you to use powerful computers to do complicated calculations with Jupyter Notebooks.
Pyomeca is a great library for working with typical biomechanics data including EMG, markers, force plates, and others. Since it is open source, you can see how the code works or “fork“ the repository to make your own changes to the library.
Happy coding!