Hướng dẫn run matlab from python

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 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.

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, 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 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

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.

Learn More