This post is the first post on the series A trick you don’t know about Python: MATLAB.

Simplifying integration between programming languages is critical to facilitate team collaboration and streamline product development. Frequently, I receive questions on how to integrate MATLAB with Python.

The following example showcases two different integration scenarios: integrating MATLAB code with Python in a development phase and integrating MATLAB code with Python for production.

Credit: The examples below come from a great demo by Heather Gorr.

Integrating MATLAB code with Python in Development

The key element in facilitating the call of MATLAB from Python is the MATLAB Engine API for Python. Once installed, you may use it to call MATLAB functions and exchange data between Python and MATLAB by using the classes included in the matlab package.

We start by calling the matlab.engine.start_matlab function, which starts a new MATLAB process in the background:

import matlab.engine
eng = matlab.engine.start_matlab()

The eng object now enables you to pass data and call functions executed by MATLAB:

x = eng.sqrt(42.0)
print(x)
6.48074069840786

which tells MATLAB to compute the square root of 42.0 by calling sqrt.

You can then call your Python code:

import weather
json_data = weather.get_current_weather("Boston","US",apikey)
data = weather.parse_current_json(json_data)
print(data)
{'temp': 45, 'feels_like': 38.91, 'temp_min': 41, 'temp_max': 48.99, 'pressure': 1010, 'humidity': 76, 'speed': 12.66, 'deg': 270, 'lon': -71.0598, 'lat': 42.3584, 'city': 'Boston', 'current_time': '2021-04-20 10:54:13.569727'}

and call any user-defined functions developed in MATLAB:

aq = eng.predictAirQual(data)
print(aq)
Good

outputing a native str Python data type.

Finally, you can exit the engine using the exit function:

eng.exit()

Enabling debugging workflows is vital to facilitate code integration. In this sense, the MATLAB Engine API provides various ways to start up the engine in desktop mode:

eng = matlab.engine.start_matlab("-desktop")

or using matlab.engine.connect_matlab to connect Python to a previously shared MATLAB session:

eng = matlab.engine.connect_matlab()

Check how to connect Python to a Running MATLAB Session.

Integrating MATLAB code with Python in Production

Another relevant use case of integrating MATLAB code with Python is when the Python user incorporates a MATLAB package created using MATLAB Compiler SDK. In this case, we are replacing MATLAB Engine for the MATLAB runtime so that you can call the MATLAB code without a MATLAB license.

Assuming the user-defined function in MATLAB predictAirQual has been packaged into the AirQual python package, the code runs as follows:

# Import the package created from MATLAB
import AirQual

# Initializing MATLAB runtime
aq = AirQual.initialize()

# Calling packaged MATLAB function
label = aq.predictAirQual(data)

# Terminating MATLAB runtime
aq.terminate()

Additionally, another very convenient mechanism aligned with scalable and secure architecture designs can be realized by using MATLAB Production Server. MATLAB Production Server is an application server that allows us to operationalize your models or algorithms through APIs, integrating them with the IT and OT systems available in your organization. So, once the development is completed in MATLAB, we can take it to Production Server and simply access those algorithms and models in a function-as-a-service manner, invoking functions via a RESTful API using JSON payloads for input and output:

from urllib import request
import json

# Server address 
url = "http://localhost:9910/AirQualReport/CurrentAirQual"

# Prep json inputs to call MATLAB code 
headers = {"Content-Type": "application/json"}
body = json.dumps({"nargout": 2, "rhs" : "San Jose"})
# Convert to string and encode
body = str(body)
body= body.encode("utf-8")

# Post method
req = request.Request(url, data=body, headers=headers)
# Response
resp = request.urlopen(req)
result = json.loads(resp.read())
print(result)
{'lhs': [{'mwdata': ['Good'], 'mwsize': [1, 4], 'mwtype': 'char'}, {'mwdata': [55.76], 'mwsize': [1, 1], 'mwtype': 'double'}]}

Want to learn more about how the integration can simplify some of your Python workflows?

Stay tuned for part 2!

Comments