- How to Call MATLAB from Python
- Call MATLAB from Python
- Functions
- Python Functions
- MATLAB Functions
- Classes
- Python Classes
- Topics
- Installing
- Getting Started
- Session Management
- Using MATLAB Workspace
- Data Exchange and Mapping
- Calling MATLAB Functions
- Troubleshooting
- Related Information
- Using MATLAB with Python
- Calling MATLAB from Python
- Calling Python Libraries from MATLAB
- Packaging MATLAB Programs for Scalable Deployment with Python
How to Call MATLAB from Python
This video is a companion to the video about calling Python ® from MATLAB. It shows how to call MATLAB ® code from Python using a sentiment analysis example. In this example, Python is used for listening to audio through a microphone and detecting text from speech. Then a pretrained machine learning model in MATLAB is used to predict the sentiment (positive, negative, or neutral) of the detected text. First, you will see how the MATLAB Engine API for Python can be used to directly call MATLAB as a computational engine from Python code. Next, you will learn how to deploy MATLAB code as a Python package using MATLAB Compiler SDK™. This deployed package requires only the MATLAB Runtime, which enables you to share your code royalty free with users who do not need MATLAB.
In this video, you will learn how to call MATLAB code from Python.
To do this, we will use a sentiment analysis example. Suppose a person says that was the best concert they ever attended. A sentiment analysis algorithm will look at this text and output what it thinks is the intent – or the sentiment – of the person. In this case, it should predict that this is a positive statement. On the other hand, if the person says they dropped their ice cream on the floor and they are sad, then the algorithm should predict a negative sentiment.
The sentiment analysis program might look like this. We listen to an audio source like a microphone, detect text from the audio signal, and then classify the text using our sentiment analysis model. Suppose I am doing all my development in Python, but my colleague already has MATLAB code to perform sentiment analysis on text. Instead of rewriting code or finding a new solution, I want to still use the MATLAB code for sentiment analysis and do the rest of my work in Python.
There are two approaches for calling MATLAB code from Python. The first is to use the MATLAB Engine API for Python, which requires a MATLAB install. The second is to use MATLAB Compiler SDK to compile a Python package that does not require users to have a MATLAB install.
Let’s first see our MATLAB code. This is a simple test script where I can write a sentence and pass it into my sentiment analysis function. The idea is to call this same function from the rest of our code that is written in Python. As you can see, the predicted sentiment is neutral, which seems correct. If you’re wondering what’s in this function, I am using a built-in sentiment analysis algorithm called VADER from Text Analytics Toolbox.
Now, let’s go to Python. I have a module that uses the SpeechRecognition package, and particularly the PocketSphinx software from Carnegie Mellon University, to recognize text from speech. In this package, my colleague provided a “speechToText” function. This listens to an audio device, such as a microphone, and returns the detected text and a Boolean flag indicating whether the detection was successful.
Here is a notebook showing the process using the MATLAB Engine API for Python. Recall that this approach requires the user to have a licensed installation of MATLAB on their machine.
I will first import the speech recognition and MATLAB Engine modules.
Then, I will start a new MATLAB process which returns an object for communicating with this process.
Let’s use the built-in “speechToText” function in our module to listen to my microphone and display the detected text. For example, “I went to my favorite restaurant and had a delicious meal”.
Now that we have the detected text, it’s time to call the MATLAB code. With this line of code, I am instructing MATLAB to call the “sentimentAnalysisVADER” function. My inputs are the detected text, and the number of output arguments I want to assign – in this case, two. As you can see from the printed outputs, the predicted sentiment is positive.
Now that we are done running MATLAB code, let’s shut down the session.
Let’s explore the second approach which is to compile a Python package from our MATLAB code. To do this, I will go to the Apps tab in MATLAB and open the Library Compiler app. I will select an output type of “Python Package” and then add my “sentimentAnalysisVADER” function for export.
You can fill in the rest of the settings with useful information and documentation, but I will jump ahead to the “Samples” section. Here is where you can provide sample code that calls your exported functions, and the Library Compiler app will automatically generate equivalent Python samples to show you how to call the package. Let’s add our test script from earlier.
Now, we can select “Package” to create our standalone component. When this is done, I can look at the output folder, and in the “samples” folder you can see the Python equivalent of the MATLAB test script I provided.
Going back to Python, here is my notebook showing the compiled package approach. Users can run these compiled packages with the MATLAB Runtime, which you can directly share with your users, or they can download it from the MathWorks website.
Note that, before running this code, both the compiled package and MATLAB Runtime need to be installed. Please refer to the documentation for steps on how to do this.
I will first import the speech recognition module and the package we just generated.
Then, I will call the “initialize” function of the compiled package to start a MATLAB Runtime.
Let’s use the built-in “speechToText” function in our module to listen to my microphone and display the detected text. For example, “I wanted to go outside but the weather is terrible ”.
Now that we have the detected text, we can call the “sentimentAnalysisVADER” function. My inputs are the detected text, and the number of output arguments I want to assign – in this case, two. As you can see from the printed outputs, the predicted sentiment is negative.
And finally, let’s terminate the MATLAB Runtime.
That concludes our example. To summarize, let’s talk about why you would want to call MATLAB from Python. The workflow we showed fits if you are already working in Python and want to use MATLAB to solve part of the problem. This could be either that you have existing MATLAB code you would like to reuse, or you need to access functionality that is only available in MATLAB and its various toolboxes and add-ons. In addition, you can use MATLAB Compiler SDK to compile Python packages that can be shared with users that do not have MATLAB installed.
To learn more, check out the resources below. Also, make sure to watch our other video on how to call Python from MATLAB.
Call MATLAB from Python
The MATLAB Engine API for Python provides a package for Python to call MATLAB as a computational engine. The engine supports the reference implementation (CPython). For supported version information, see Versions of Python Compatible with MATLAB Products by Release.
Engine applications require an installed version of MATLAB; you cannot run the MATLAB engine on a machine that only has the MATLAB Runtime.
Functions
Python Functions
matlab.engine.start_matlab | Start MATLAB Engine for Python |
matlab.engine.find_matlab | Find shared MATLAB sessions to connect to MATLAB Engine for Python |
matlab.engine.connect_matlab | Connect shared MATLAB session to MATLAB Engine for Python |
MATLAB Functions
matlab.engine.shareEngine | Convert running MATLAB session to shared session |
matlab.engine.engineName | Return name of shared MATLAB session |
matlab.engine.isEngineShared | Determine if MATLAB session is shared |
Classes
Python Classes
matlab.engine.MatlabEngine | Python object using MATLAB as computational engine within Python session |
matlab.engine.FutureResult | Results of asynchronous call to MATLAB function stored in Python object |
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
MATLAB Engine API for Python provides a Python package named matlab 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.
Session Management
- Connect Python to Running MATLAB Session
How to connect the MATLAB Engine for Python to a shared MATLAB session that is already running on your local machine.
Using MATLAB Workspace
- Use MATLAB Engine Workspace in Python
This example shows how to add variables to the MATLAB engine workspace in Python.
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 MATLAB sqrt function. - MATLAB Arrays as Python Variables
The matlab 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, 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 MATLAB sqrt 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 Python StringIO objects.
Troubleshooting
MATLAB Engine API for Python does not support these features.
When a MATLAB function raises an error, the MATLAB Engine for Python stops the function and catches the exception raised by MATLAB.
Related Information
Using MATLAB with Python
MATLAB ® provides a flexible, two-way integration with many programming languages, including Python. This allows different teams to work together and use MATLAB algorithms within production software and IT systems.
Calling MATLAB from Python
The MATLAB Engine API for Python allows you to call MATLAB as a computational engine from Python.
The API lets you execute MATLAB commands from within your Python environment without starting a desktop session of MATLAB. Learn more about the MATLAB Engine API for Python.
Calling Python Libraries from MATLAB
If you have functions and objects in Python, you can call them directly from MATLAB.
This allows you to work entirely within MATLAB without switching your programming environment. Learn more about calling Python libraries from MATLAB.
Packaging MATLAB Programs for Scalable Deployment with Python
Write algorithms and applications in MATLAB, and package and share them with just one click. You can build Python packages from MATLAB programs by using MATLAB Compiler SDK™. These packages can be integrated with Python applications that, in turn, can be shared with desktop users or deployed to web and enterprise systems, royalty-free. Learn more about integrating compiled MATLAB programs into Python applications.
Scale up your MATLAB programs to concurrently access and serve a system of databases, web, and enterprise applications by deploying the programs to MATLAB Production Server™. The server provides integration within your IT architecture via lightweight client API libraries (that include Python) and a RESTful/JSON interface.