Call matlab from python example

Use the MATLAB® Engine API for Python® to call any MATLAB function on the MATLAB path.

If the MATLAB function is not on the path, you can call it from the current folder. For example, to call MATLAB function myFnc in folder myFolder, type:

import matlab.engine
eng = matlab.engine.start_matlab()
eng.cd(r'myFolder', nargout=0)
eng.myFnc()

Return Output Argument from MATLAB Function

You can call any MATLAB function directly and return the results to Python. For example, to determine if a number is prime, use the engine to call the isprime function.

import matlab.engine
eng = matlab.engine.start_matlab()
tf = eng.isprime(37)
print(tf)

Return Multiple Output Arguments from MATLAB Function

When you call a function with the engine, by default the engine returns a single output argument. If you know that the function can return multiple arguments, use the nargout argument to specify the number of output arguments.

To determine the greatest common denominator of two numbers, use the gcd function. Set nargout to return the three output arguments from gcd.

import matlab.engine
eng = matlab.engine.start_matlab()
t = eng.gcd(100.0,80.0,nargout=3)
print(t)

Return No Output Arguments from MATLAB Function

Some MATLAB functions return no output arguments. If the function returns no arguments, set nargout to 0.

Open the MATLAB Help browser from Python.

import matlab.engine
eng = matlab.engine.start_matlab()
eng.doc(nargout=0)

The MATLAB doc function opens the browser, but does not return output arguments. If you do not specify nargout=0, the engine raises an error.

Stop Execution of Function

To stop execution of a MATLAB function press Ctrl+C. Control returns to Python.

Use Function Names for MATLAB Operators

You can use a MATLAB operator in Python by calling the equivalent function. For a list of operators and associated function names, see MATLAB Operators and Associated Functions. For example, to add two numbers, use the plus function instead of the + operator.

import matlab.engine
eng = matlab.engine.start_matlab()
a = 2
b = 3
eng.plus(a,b) 

See Also

matlab.engine.MatlabEngine | matlab.engine.FutureResult

  • Call MATLAB Functions Asynchronously from Python
  • Call User Scripts and Functions from Python
  • Use MATLAB Arrays in Python
  • Sort and Plot MATLAB Data from Python

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

Can I call a MATLAB function from 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.

How do I call a MATLAB file in Python?

Start MATLAB Engine for Python.
Start Python® at the operating system prompt..
Import the matlab. engine package into your Python session..
Start a new MATLAB® process by calling start_matlab . The start_matlab function returns a Python object eng which enables you to pass data and call functions executed by MATLAB..

How does MATLAB integrate with Python?

To integrate a MATLAB® Compiler SDK™ Python® Package:.
In consultation with the MATLAB programmer, collect the MATLAB function signatures that comprise the services in the application..
Install and import the compiled Python package. ... .
Write the Python code to initialize MATLAB Runtime and load the MATLAB code..

How do I run MATLAB code in Pycharm?

I successfully run the MATLAB code on Pycharm, let main.py is your main python file that start the python project. you need to put the invoked matlab files in the same folder './' of the main.py that starts the program and inside the main.py you need to import the engine: import matlab.