Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Using MATLAB® and Python® Together

The ≥ icon provides links to relevant sections of the MATLAB documentation to


learn more.

Call Python in MATLAB Call MATLAB in Python Create Python Package


Access settings and status of Python Install MATLAB Engine API for Python Package MATLAB functions
interpreter: Run setup.py from an OS command window Use the Library Compiler App to create a
>> pe = pyenv $ cd [matlabroot]/extern/engines/python Python package for MATLAB functions
$ python setup.py install
Specify version to use:
>> pe = pyenv("Version",3.7) Call MATLAB functions
Import the module and start the engine
Call Python modules and functions: >>> import matlab.engine
py.module _ name.function _ name >>> eng =
matlab.engine.start _ matlab()
>> py.math.sqrt(42)
Call functions through the engine Invoke MATLAB functions from the Python
Pass keyword arguments >>> x = eng.sqrt(42.0) package
Use pyargs to pass keyword arguments >>> import PackageName
>>> foo(5,bar=42) Capture multiple outputs >>> pkg =
>> py.foo(5,pyargs('bar',42)) >>> x = eng.gcd(42.0,8.0,nargout=3) PackageName.initialize()
>>> result = pkg.foo()
Reload modules Stop the engine
Reload the module after making >>> eng.exit() Close package
updates: >>> pkg.terminate()
>> py.importlib.reload(module)

Data Type Conversions Data Science Libraries


Data types will be automatically Some MATLAB data types need to be Apache Parquet
converted where possible. converted.

MATLAB Python MATLAB Conversion Function


double, single float categorical char
complex single complex string char
complex double table table2struct
Use Apache Parquet to efficiently transfer tabular
(u)int8, (u)int16, int data
timetable timetable2struct
(u)int32,(u)int64 From MATLAB:
datetime char >> tbl = parquetread(fname)
NaN float(nan)
Note: The default numeric type is integer in >> parquetwrite(tbl,fname)
Inf float(inf)
Python and double in MATLAB when typing 42
String, char str From Python:
Logical bool >>> df = pandas.read _ parquet(fname)
To create a float in Python:
Structure dict >>> x = 42.0 >>> pandas.Dataframe.to _ parquet(df)
Vectors array.array() >>> x = float(42)
Deep Learning
Cell array list, tuple
Create integer from MATLAB: Access frameworks in MATLAB with importers for
>> x = int32(42) Tensorflow-Keras, ONNX, etc
>> net = importKerasNetwork(model)

mathworks.com

© 2020 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.
Other product or brand names may be trademarks or registered trademarks of their respective holders.

You might also like