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")
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)
MATLAB | Python |
Double, single |
Float |
complex single |
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 |
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.