Skip to content
Related Articles

Related Articles

Improve Article

Calling a Python function from MATLAB

  • Last Updated : 24 May, 2021

We can call the Python functions and objects directly from MATLAB. To call Python functions from MATLAB, need to install a supported version of  Python. MATLAB supports versions 2.7, 3.6, and 3.7

MATLAB  loads Python when you type py.command.


Below examples shows how to call a user defined Python function from MATLAB.

Example 1 :

Call Python function to print Hello. 
First of all, we will make a Python module named containing the function.


# Python Module -
def printHello:
    return "Hello"

Now, open a new file in MATLAB Editor. Verify whether the current folder pointed to the Python search path. Use below code to add the current folder to Python search path.


if count(py.sys.path, '') == 0
  insert(py.sys.path, int32(0), '');

Call the Python function to print Hello.



Output : 



Example 2 : Call Python function to get the sum of two numbers.

First of all, we will create a Python module names containing the function.


# Python Module -
def addgivenNumbers( num1, num2):
    sum = num1 + num2
    return sum

Call Python function to get the sum of two given numbers


py.add.addgivenNumbers(int32(2), int32(3));

Output : 



 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :