Main Content
Write Python® programs that work with MATLAB®
Functions
expand all
Python Functions
MATLAB Functions
Topics
Installing
- System Requirements for MATLAB Engine API for Python
What you need to write and build MATLAB engine applications for Python. - Install MATLAB Engine API for Python
To start MATLAB engine within a Python session, install the engine API as a Python package.
- Python Setup Script to Install MATLAB Engine API
- Install MATLAB Engine API for Python in Nondefault Locations
Getting Started
- Get Started with MATLAB Engine API for Python
The MATLAB Engine API for Python provides a Python package namedmatlab
that enables you to call MATLAB functions from Python. - Start and Stop MATLAB Engine for Python
Options for starting the MATLAB Engine for Python. - Call MATLAB Functions from Python
How to return an output argument from a MATLAB function. How to read multiple outputs from a function. What to do when the MATLAB function does not return an output argument. - Get Help for MATLAB Functions from Python
From Python, you can access supporting documentation for all MATLAB functions.
Data Exchange and Mapping
- Use MATLAB Arrays in Python
This example shows how to create a MATLAB array in Python and pass it as the input argument to the MATLABsqrt
function. - MATLAB Arrays as Python Variables
Thematlab
Python module provides array classes to represent arrays of MATLAB numeric types as Python variables so that MATLAB arrays can be passed between Python and MATLAB. - Pass Data to MATLAB from Python
When you pass Python data as input arguments to MATLAB functions, the MATLAB Engine for Python converts the data into equivalent MATLAB data types. - Handle Data Returned from MATLAB to Python
When MATLAB functions return output arguments, the MATLAB Engine API for Python converts the data into equivalent Python data types. - Use MATLAB Handle Objects in
Python
This example shows how to create an object from a MATLAB handle class and call its methods in Python. - Default Numeric Types in MATLAB and Python
MATLAB stores all numeric values as double-precision floating point numbers by default.
Calling MATLAB Functions
- Call User Scripts and Functions from Python
This example shows how to call a MATLAB script to compute the area of a triangle from Python. - Sort and Plot MATLAB Data from Python
This example shows how to sort data about patients into lists of smokers and nonsmokers in Python and plot blood pressure readings for the patients with MATLAB. - Call MATLAB Functions Asynchronously from Python
This example shows how to call the MATLABsqrt
function asynchronously from Python and retrieve the square root later. - Redirect Standard Output and Error to Python
This example shows how to redirect standard output and standard error from a MATLAB function to PythonStringIO
objects.
Troubleshooting
Supported platforms: Windows®, Linux®, Mac
This example shows how to create a Python® package from a MATLAB® function and integrate the generated package into a Python application.
Prerequisites
Verify that you have a version of Python installed that is compatible with MATLAB Compiler SDK™. For details, see MATLAB Supported Interfaces to Other Languages.
End users must have an installation of MATLAB Runtime to run the application. For testing purposes, you can use an installation of MATLAB instead of MATLAB Runtime. For details, see Install and Configure MATLAB Runtime.
Create Function in MATLAB
In MATLAB, examine the MATLAB code that you want packaged. For this example, create a function named makesqr.m
that
contains the following code:
function y = makesqr[x]
y = magic[x];
At the MATLAB command prompt, enter makesqr[5]
.
The output is a 5-by-5 matrix.
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
Create Python Application Using Library Compiler App
Compile the function into a Python package using the Library Compiler app. Alternatively, if you want to create a Python package from the MATLAB command window using a programmatic approach, see Create Python Package Using compiler.build.pythonPackage.
On the MATLAB Apps tab, on the far right of the Apps section, click the arrow. In Application Deployment, click Library Compiler.
Alternatively, you can open the Library Compiler app from the MATLAB command prompt.
In the Type section of the toolstrip, click Python Package.
In the Library Compiler app project window, specify the files of the MATLAB application that you want to deploy.
In the Exported Functions section of the toolstrip, click
.In the Add Files window, browse to the example folder, and select the function you want to package. Click Open.
The function is added to the list of exported function files. Repeat this step to package multiple files in the same application.
For this example, select the
makesqr.m
file that you wrote earlier.In the Packaging Options section of the toolstrip, decide whether to include the MATLAB Runtime installer in the generated application by selecting one of the options:
Runtime downloaded from web — Generate an installer that downloads the MATLAB Runtime and installs it along with the deployed MATLAB application. You can specify the file name of the installer.
Runtime included in package — Generate an application that includes the MATLAB Runtime installer. You can specify the file name of the installer.
Note
The first time you select this option, you are prompted to download the MATLAB Runtime installer.
Specify Package Settings
Next, define the name of your Python package.
Choose a name for your package. The Library Name field is automatically populated with
makesqr
as the name of the package. Rename it asMagicSquarePkg
. For more information on naming requirements for the Python package, see Install and Import MATLAB Compiler SDK Python Packages.
Create Sample Driver File
You can add MATLAB files to the project to generate sample Python driver files. Although Python driver files are not necessary to create a package, you can use them to implement a Python application, as shown in Install and Run MATLAB Generated Python Application.
In the Samples section, select Create New Sample, and click makesqr.m
. A MATLAB file opens for you to edit.
% Sample script to demonstrate execution of function y = makesqr[x] x = 0; % Initialize x here y = makesqr[x];
Change x = 0
to x = 5
, save the file, and return
to the Library Compiler app.
For more information and limitations, see Sample Driver File Creation.
Customize the Application and Its Appearance
In the Library Compiler app, you can customize the installer, customize your application, and add more information about the application.
Library information — Information about the deployed application. You can also customize the appearance of the application by changing the application icon and splash screen. The generated installer uses this information to populate the installed application metadata. See Customize the Installer.
Additional installer options — Default installation path for the generated installer and custom logo selection. See Change the Installation Path.
Files required for your library to run — Additional files required by the generated application to run. These files are included in the generated application installer. See Manage Required Files in Compiler Project.
Files installed for your end user — Files that are installed with your application.
See Specify Files to Install with Application.
Package the Application
When you are finished selecting your packaging options, save your Library Compiler project and generate the packaged application.
Click Package.
In the Save Project dialog box, specify the location to save the project.
In the Package dialog box, verify that Open output folder when process completes is selected.
When the packaging process is complete, examine the generated output in the target folder.
Three folders are generated:
for_redistribution
,for_redistribution_files_only
, andfor_testing
.For more information about the files generated in these folders, see Files Generated After Packaging MATLAB Functions.
-
The log file
PackagingLog.html
contains packaging results.
Create Python Package Using compiler.build.pythonPackage
As an alternative to the Library Compiler app, you can create a Python package using a programmatic approach. If you have already created a package using the Library Compiler, see Install and Run MATLAB Generated Python Application.
Save the following code in a sample file named
makesqrSample1.m
:Build the Python package using the
compiler.build.pythonPackage
function and themakesqr.m
file that you wrote earlier. Use name-value arguments to specify the package name and add a sample file.buildResults = compiler.build.pythonPackage['makesqr.m', ... 'PackageName','MagicSquarePkg', ... 'SampleGenerationFiles','makesqrSample1.m', ... 'Verbose','on'];
You can specify additional options in the
compiler.build
command by using name-value arguments. For details, seecompiler.build.pythonPackage
.The
compiler.build.Results
objectbuildResults
contains information on the build type, generated files, included support packages, and build options.The function generates the following files within a folder named
MagicSquarePkgpythonPackage
in your current working directory:samples\makesqrSample1.py
— Python sample application file.GettingStarted.html
— HTML file that contains information on integrating your package.includedSupportPackages.txt
— Text file that lists all support files included in the package.mccExcludedFiles.log
— Log file that contains a list of any toolbox functions that were not included in the application. For information on non-supported functions, see MATLAB Compiler Limitations.readme.txt
— Text file that contains packaging and interface information.requiredMCRProducts.txt
— Text file that contains product IDs of products required by MATLAB Runtime to run the application.setup.py
— Python file that installs the package.unresolvedSymbols.txt
— Text file that contains information on unresolved symbols.
Note
The generated package does not include MATLAB Runtime or an installer. To create an installer using the
buildResults
object, seecompiler.package.installer
.
Install and Run MATLAB Generated Python Application
After creating your Python package, you can call it from a Python application. This example uses the sample Python code generated during packaging. You can use this sample Python application code as a guide to write your own application.
Copy and paste the generated Python file
makesqrSample1.py
from thesamples
folder into the folder that contains thesetup.py
file.The program listing for
makesqrSample1.py
is shown below.#!/usr/bin/env python """ Sample script that uses the MagicSquarePkg module created using MATLAB Compiler SDK. Refer to the MATLAB Compiler SDK documentation for more information. """ from __future__ import print_function import MagicSquarePkg import matlab my_MagicSquarePkg = MagicSquarePkg.initialize[] xIn = matlab.double[[5.0], size=[1, 1]] yOut = my_MagicSquarePkg.makesqr[xIn] print[yOut, sep='\n'] my_MagicSquarePkg.terminate[]
At the system command prompt, navigate to the folder that contains
makesqrSample1.py
andsetup.py
.Install the application using the
python
command.To install to a location other than the default, consult "Installing Python Modules" in the official Python documentation.
Run the application at the system command prompt.
If you used sample MATLAB code in the packaging steps, this application returns the same output as the sample code.
[[17.0,24.0,1.0,8.0,15.0],[23.0,5.0,7.0,14.0,16.0],[4.0,6.0,13.0,20.0,22.0], [10.0,12.0,19.0,21.0,3.0],[11.0,18.0,25.0,2.0,9.0]]
Note
On macOS, you must use the
mwpython
script instead ofpython
. For example,mwpython makesqrSample1.py
.The
mwpython
script is located in the
folder, wherematlabroot
/binmatlabroot
is the location of your MATLAB or MATLAB Runtime installation.
See Also
mwpython
|
libraryCompiler
|
compiler.build.pythonPackage
|
mcc
|
deploytool
Related Topics
- Install and Import MATLAB Compiler SDK Python Packages
- Create Python Application with Multiple MATLAB Functions