December 16, 2024

Tutorial on how to Execute Python Code Directly From MATLAB

In this tutorial, we explain how to execute Python code from MATLAB. The motivation for creating this post comes from the fact that it is often necessary to execute a piece of code directly from MATLAB. For example, imagine that you wrote a piece of code in MATLAB. This code performs basic matrix operations and computes a single matrix as the result. Then, you need to send this matrix to a Python code file that you developed. This Python code should receive this matrix, and perform some additional operations on this matrix or call a machine learning library, such as TensorFlow, by specifying this matrix as an input. Then, after Python code completes its operation, it should send back the result to MATLAB. In such cases, we need to develop an interface between MATLAB and Python. That is, we need to call Python code directly from MATLAB and we need to specify inputs and outputs. By learning how to do that, you can create a powerful computation and programming environment. The GitHub code with all the codes presented in this tutorial is given here. The YouTube video accompanying this tutorial is given below.

To make a long story short, we will write MATLAB and Python codes that will perform the following operations. First, we define two matrices and a parameter in MATLAB, then we pass these matrices and the parameter to Python, Python performs some operations and returns the resulting matrices back to MATLAB. This is a classical problem that you might experience and that you need to solve.

Prerequisites and First Steps

First of all, the approach presented in this tutorial requires a MATLAB version of at least R2021b or higher. Not every Python version is supported by every MATLAB version. First of all, check your MATLAB version by typing in MATLAB the command “ver”. In my case, I obtained the reply “R2021b”. Then, you need to follow this MATLAB link , to see if the current Python version that you are using is supported by your MATLAB version. In my case, for the MATLAB version R2021b, I see that the following Python versions are supported: 3.7, 3.8, 3.9. Since initially, I did not have any of these Python versions, I installed Python 3.9, by downloading the installation file and by running it.

Then, you need to make sure that MATLAB is able to recognize this Python version and you need to tell to MATLAB that you will be using this specific Python version. You can do that by typing the following code lines in MATLAB

pyenv('Version','enter path to your python executable here')

where ‘enter path to your python executable here’ is the path to your “python.exe” file that you need to specify. In my case, the file is located here

C:\Users\ahaber\AppData\Local\Programs\Python\Python39\python.exe

So, I have to type this in MATLAB

pyenv('Version','C:\Users\ahaber\AppData\Local\Programs\Python\Python39\python.exe')

Then, after this, we can check if the everything is OK, by running

pe = pyenv;
pe.Version

And you should get messages stating that the proper Python version is linked to MATLAB with some other messages.

Next, you need to make sure that the proper libraries are installed in your Python environment. This is especially the case, if you previously had a Python version before the new Python version that you installed and that is required by MATLAB. For example, in my case, I had Python 3.11, so I had to install Python 3.9, while keeping the Python 3.11. Note that in my PATH Windows file, Python 3.11 is the default version. So, if I type “pip install library_name” in the Windows command line, I will only install the library in Python 3.11 environment. To make sure that the correct libraries are installed in Python 3.9 (version that is linked to MATLAB), you need to run Python 3.9 from the command line, and then in the Python environment, you need to install the correct libraries. You can do that like this (I will use my paths, and you need to change the commands depending on your code). First, open the Windows command terminal and type

cd C:\Users\ahaber\AppData\Local\Programs\Python\Python39

This will lead you to the Python 3.9 installation folder. Then you need to type

python

This will open the Python terminal. Then, let us say that I want to install NumPy and SciPy libraries. I can do that by typing in the Python environment the following code lines:

import sys
import subprocess
subprocess.check_call([sys.executable, '-m', 'pip', 'install','numpy'])
subprocess.check_call([sys.executable, '-m', 'pip', 'install','scipy'])

The last two code lines will install NumPy and SciPy libraries. After that, we are ready to go.

Python Code that is called from MATLAB

Here is the Python code that will be called from MATLAB.

import numpy as np
from scipy import linalg

C1=A+B
C2=np.matmul(A,B)
C3=np.eye(param1,param1)
C4=linalg.inv(A)

# this list is returned to MATLAB and later on unpacked in MATLAB
ReturnList=[C1,C2,C3,C4]

“A” and “B” are two matrices. We perform various matrix operations on these two matrices. In addition, we define an identity matrix. Note here that “A”,”B”, and “param1” are not defined or declared in this code. So if you try to execute this piece of code independently from the MATLAB code that will be explained in the sequel, you will obtain an error. In fact these variables are sent to Python directly from MATLAB as you will see later. At the end of this code, I define a list, called “ReturnList” that is sent back to MATLAB. Note here that Python code does not send anything directly to MATLAB. As you will see later, MATLAB will actually read these variables from the Python workspace.

You need to save this code as “test.py”.

MATLAB code that calls Python code

First, we need to define two matrices and the parameter. This is done by the following code lines in MATLAB

% define MATLAB matrices
A1=[1 2;
    3 4];
A2=[2 3;
    1 0];

% check the conversion types
% https://www.mathworks.com/help/matlab/matlab_external/passing-data-to-python.html
% convert matrices to Python objects
A1converted = py.numpy.array(A1);
A2converted = py.numpy.array(A2);
% parameter to be sent
parameter=py.int(2);

Basically, we define two matrices A1 and A2 in MATLAB. Then, we convert these matrices to Python objects in MATLAB. This is done by typing py.numpy.array(). Then, we define a parameter “parameter” that is sent to Python. This parameter is another Python object. In our case, it is an integer equal to 2. Note that this integer is used to define the dimension of an identity matrix in the Python code. We call the Python code and return the result by using this command line in MATLAB

% sent the variables, call the python code in "test.py" and obtain the
% return list "result"
[result] = pyrunfile("test.py","ReturnList",A=A1converted,B=A2converted,param1=parameter)
% link explaining pyrunfile() function:
% https://www.mathworks.com/help/matlab/ref/pyrunfile.html#mw_03ecec06-0677-4345-9112-ea93ac49881e

The first argument of the function “pyrunfile()” is the name of the Python file that we are calling. The second argument is the name of the variable in our Python code that will be returned by this function. The last three arguments are variables that are sent to the Python code. We basically say that “A” in the Python code is “A1converted”, “B” in the Python code is “A2converted”, and “param1” in the Python code is “parameter”. This function will call the Python code in “test.py”, it will execute the code, and it will read the list “ReturnList”. This list is assigned to variable “result” in MATLAB.

We can check the data type of “result” as follows in MATLAB

% check the data type of returned variables
class(result)
class(result{1})

We obtain

ans =

    'py.list'


ans =

    'py.numpy.ndarray'

which means that these are the Python objects in MATLAB workspace. We can extract the results in MATLAB as follows

% convert the Python arrays to MATLAB matrices
C1=double(result{1});
C2=double(result{2});
C3=double(result{3});
C4=double(result{4});

To double check the result, we can perform the same operations in MATLAB

% compute the matrices in MATLAB to double check the results
C1check=A1+A2;
C2check=A1*A2;
C3check=eye(2,2);
C4check=inv(A1);

By comparing the result, we can see that the results obtained by Python and MATLAB code are identical.

That is it. You can easily modify the presented idea to solve your problem. The complete code is given on the GitHub page. Please support this webpage.