Easily integrate Custom Functions in MATLAB with Python (codes included)

Utpal Kumar   6 minute read      

Introduction

MATLAB implementation are usually quite reliable as it is developed by the professionals. But the advantages of using Python is immense. In this post, I will show how you can benefit the MATLAB function in your Python script.

Key idea — two bridges, chosen by who runs the code. If you (or anyone with MATLAB installed) will run the script, the MATLAB Engine API for Python is the quickest route: import matlab.engine, start a session, and call your .m functions directly. If you need to ship the code to someone without MATLAB, use the MATLAB Compiler SDK to package the function into a Python library that runs against the free MATLAB Runtime. Either way, you pass data across the boundary using MATLAB’s typed wrappers (matlab.double, etc.) and get results back as Python objects.

Defining custom function in MATLAB

Let us make a custom function in MATLAB that we can use in Python. For the purpose of demonstration, I will use a very simple function but the same idea applies to any function.

Eigenvalues and eigenvectors in MATLAB

function [V,D] = eigFunc(A)
%returns diagonal matrix D of eigenvalues and matrix V 
% whose columns are the corresponding right eigenvectors, 
% so that A*V = V*D.
[V, D] = eig(A);
end

I saved the above function as eigFunc. This function takes in a square matrix as input and outputs diagonal matrix D of eigenvalues and matrix V whose columns are the corresponding right eigenvectors [see eig function in MATLAB].

Let’s first use this function in MATLAB for test purpose.

clear; close all; clc
A = gallery('lehmer',4);

[V,D] = eigFunc(A)

This returns:

V =

    0.0693   -0.4422   -0.8105    0.3778
   -0.3618    0.7420   -0.1877    0.5322
    0.7694    0.0486    0.3010    0.5614
   -0.5219   -0.5014    0.4662    0.5088


D =

    0.2078         0         0         0
         0    0.4078         0         0
         0         0    0.8482         0
         0         0         0    2.5362

This works great in MATLAB as expected (coz the function is exact copy of the eig function in MATLAB. But how can we use this function in Python?

Call MATLAB in Python

There are two routes, and which one you pick depends on whether the person running the code has MATLAB installed:

Two ways to call MATLAB from Python Route A uses the MATLAB Engine API: a Python script imports matlab.engine and drives a live MATLAB session, which needs MATLAB installed and licensed. Route B uses MATLAB Compiler SDK to turn a MATLAB function into a Python package that runs against the free MATLAB Runtime, so the end user needs no MATLAB install. Two ways to call MATLAB from Python A · Engine API — for development Python script your .py matlab.engine Live MATLAB session start_matlab() · eng.eigFunc(...) needs MATLAB installed + licensed B · Compiler SDK + Runtime — for deployment MATLAB .m eigFunc.m Compiler Python package importable wheel Runs in any Python no MATLAB install MATLAB Runtime free download
Route A (Engine API) drives a live MATLAB session and needs MATLAB installed; Route B (Compiler + free Runtime) ships to users who have no MATLAB.

Using MATLAB Engine API for Python

The easiest way to use the matlab function in Python is by using the matlab.engine. You can install matlab library by following these two ways.

Install from inside MATLAB:

cd (fullfile(matlabroot,'extern','engines','python'))
system('python setup.py install')

Install directly from terminal:

Navigate to the MATLAB source location and compile the python. For installing matlab library in Mac:

cd /Applications/MATLAB_R2021b.app/extern/engines/python/
python setup.py install

Please note that this MATLAB engine API will be installed for the the specific version of python. If you are using anaconda, you can inspect the version of Python you are installing the MATLAB engine API for. It is essentially the same way you install other Python libraries. For details, visit here.

Simpler install since R2022b: use pip. You no longer have to run python setup.py install from inside matlabroot (and setup.py install is itself deprecated by modern setuptools). The engine is now on PyPI, so you can just run pip install matlabengine. The catch is version matching: the matlabengine release must match your installed MATLAB release — e.g. pip install matlabengine==25.1.* for R2025a — and each release supports a specific band of Python versions (the current package supports Python 3.9–3.13). Pip will list the compatible versions if you ask for one that does not match. The setup.py method above still works for older MATLAB releases.

import matlab
import matlab.engine
eng = matlab.engine.start_matlab()
A = [[1.0000,    0.5000,    0.3333,    0.2500],
     [0.5000,    1.0000,    0.6667,    0.5000],
     [0.3333,    0.6667,    1.0000,    0.7500],
     [0.2500,    0.5000,    0.7500,    1.0000]]
A = matlab.double(A)
V, D = eng.eigFunc(A, nargout=2)
print("V: ", V)
print("D: ", D)

eng.quit()

Here is the output:

V:  [[0.06939950784450351,-0.4421928183150595,-0.8104910184495989,0.37782737957175255],				[-0.3619020163563876,0.7419860358173743,-0.18770341448628555,0.5322133795757004],[0.7693553355549393,0.04873539080548356,0.30097912769034274,0.5613633351323756],[-0.5218266058004974,-0.5015447096377744,0.4661365700065611,0.5087893432606572]]

D:  [[0.20775336892808516,0.0,0.0,0.0],[0.0,0.40783672775946245,0.0,0.0],[0.0,0.0,0.8482416513967358,0.0],[0.0,0.0,0.0,2.536168251915717]]

The results are same as before. The nargout argument tells the matlab based function to output 2 results here.

Create Python Package: Using MATLAB Compiler & MATLAB Runtime

This is all well and good if you have MATLAB installed in your system. But what if you wanna give your Python script so someone who does not have MATLAB installed on their system. In that case, you can build a Python library using the library compiler app in MATLAB. For details, visit Generate a Python Package and Build a Python Application.

select library compiler app in matlab fill in information
(a) Select library compiler app in MATLAB (b) Fill in information regarding the Python library
select library compiler app in matlab Add example MATLAB script
(a) Select MATLAB function to generate the Python library (b) Add example MATLAB script
Click to package application Wait for the python library to generate
(a) Click on package to generate standalone component (b) Wait for the task to finish

MATLAB Runtime installation

Please note that, the user need to install MATLAB runtime for successfully using this library. MATLAB runtime helps in running compiled MATLAB applications or components without installing MATLAB. The runtime can be downloaded from here for Windows, Mac and Linux OS and it is free to download.

Import MATLAB based library for Python

import eigFunc
eigFuncAnalyzer = eigFunc.initialize() #calls the matlab runtime
A = [[1.0000,    0.5000,    0.3333,    0.2500],
     [0.5000,    1.0000,    0.6667,    0.5000],
     [0.3333,    0.6667,    1.0000,    0.7500],
     [0.2500,    0.5000,    0.7500,    1.0000]]
A = array.array(A) %not tested
V, D = eigFuncAnalyzer.eigFunc(A, nargout=2)
print("V: ", V)
print("D: ", D)
eigFuncAnalyzer.terminate()

Please note that you can design your eigFunc.m in a way that you can simply load the mat data and you can use scipy.io.savemat function to save the python data to mat format. For details see the scipy documentation.

Data Type Conversions

MATLAB PYTHON
double, single float
complex single complex double complex
(u)int8, (u)int16, (u)int32,(u)int64 int
NaN float(nan)
Inf float(inf)
String, char str
Logical bool
Structure dict
Vectors array.array()
Cell array list, tuple

Quick check: You want to hand your MATLAB-powered analysis to a colleague who does not have a MATLAB license. Which route works?

  • The MATLAB Engine API (import matlab.engine) — it bundles MATLAB into the package
  • Compile the function with MATLAB Compiler SDK into a Python package; the colleague installs the free MATLAB Runtime
  • Neither — you always need a full MATLAB install to run compiled MATLAB code
  • Rewrite everything in NumPy first; there is no other option

Recap

  • The MATLAB Engine API for Python (import matlab.engine, eng = matlab.engine.start_matlab()) drives a live MATLAB session from Python — quickest to set up, but every user needs MATLAB installed and licensed.
  • Since R2022b the engine installs with a plain pip install matlabengine, version-matched to your MATLAB release (no more setup.py install).
  • Pass data across the boundary with MATLAB’s typed wrappers such as matlab.double(...), and use nargout to tell a function how many outputs to return.
  • To deploy to users without MATLAB, package the function with MATLAB Compiler SDK and have them install the free MATLAB Runtime — no license required.
  • Refer to the data-type conversion table above (double↔float, struct↔dict, cell↔list/tuple, …) whenever results look wrapped in an unexpected type.

Where to go next

References

  1. How to Call MATLAB from Python
  2. Call MATLAB Functions from Python
  3. Generate a Python Package and Build a Python Application

Disclaimer of liability

The information provided by the Earth Inversion is made available for educational purposes only.

Whilst we endeavor to keep the information up-to-date and correct. Earth Inversion makes no representations or warranties of any kind, express or implied about the completeness, accuracy, reliability, suitability or availability with respect to the website or the information, products, services or related graphics content on the website for any purpose.

UNDER NO CIRCUMSTANCE SHALL WE HAVE ANY LIABILITY TO YOU FOR ANY LOSS OR DAMAGE OF ANY KIND INCURRED AS A RESULT OF THE USE OF THE SITE OR RELIANCE ON ANY INFORMATION PROVIDED ON THE SITE. ANY RELIANCE YOU PLACED ON SUCH MATERIAL IS THEREFORE STRICTLY AT YOUR OWN RISK.


Leave a comment