Cheat Sheets

Calling Python from MATLAB

This reference shows common use cases but is by no means comprehensive. 

Enhance Python with MATLAB

Integrate MATLAB’s advanced tools directly into your Python workflows.

Setup

Requirements

To call Python® from MATLAB, you need to have both installed on your system.

Configuration

Access settings and the status of the Python interpreter:

>> pe = pyenv 

Specify which version to use:

>> pe = pyenv("Version","3.9") 

Ensure the PYTHONHOME environment variable aligns with your Python version. To view its value in MATLAB:

>> getenv("PYTHONHOME") 

Ensure the appropriate versions are on the system path:

>> getenv("PATH")

Run Python Code in MATLAB

Live Editor Task

The Run Python Code task lets you interactively run Python code or files, then generate the code.

Call Python Statements

To execute a few lines of code:

>> outvars = pyrun(code,outputs) 
>> x = pyrun("a = b*c","a", b = 5, c = 10)

Call Python Script

To execute code organized in a script:

>> outvars = pyrunfile(file,outputs) 

Call Python Modules and Functions

>> py.module _ name.function _ name 
>> x = py.math.sqrt(42) 

Pass Keyword Arguments

Either call directly or use pyargs:

>>> foo(5,bar=42) 
>> py.foo(5,bar=42) 
>> py.foo(5,pyargs('bar',42)) 

Reload Modules

Reload the module after making updates:

>> py.importlib.reload(module)

Data Type Conversions

Data types will be automatically converted where possible.

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, car Str
Logical Bool
Dictionary dict
Struct dict
Table Py.pandas.dataframe
Datetime Py.datetime.datetime
Duration Py.datetime.timedelta

Data Science Libraries

Apache Parquet

Use Apache® Parquet to efficiently transfer data.

From MATLAB:

>> tbl = parquetread(fname)
>> parquetwrite(tbl,fname) 

From Python:

>>> df = pandas.read _ parquet(fname) 
>>> pandas.Dataframe.to _ parquet(df) 

Deep Learning

Access models in MATLAB with importers for TensorFlow, PyTorch®, and ONNX.

>> net = importKerasNetwork(model)

Integrate Python and Simulink

You can use the Python Importer to import Python modules and packages to Simulink.

Open the importer: 

>> obj = Simulink. PythonImporter(); 
>> obj.view(); 

MATLAB Function Block and MATLAB System Block

Implement Python modules in Simulink using MATLAB Function block or MATLAB System block.