Calling a Python function from MATLAB

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.

py.modulename.functionname

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 print.py containing the function.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python Module - print.py
  
def printHello:
    return "Hello"

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Call the Python function to print Hello.

filter_none

edit
close

play_arrow

link
brightness_4
code

py.print.printHello();

chevron_right


Output :

Hello

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

First of all, we will create a Python module names add.py containig the function.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Call Python function to get the sum of two given numbers

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

5

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.