How we can call Python function from MATLAB?


The Python libraries are now available in MATLAB (since 2014b). We can run code directly in MATLAB if we are using version 2014b or later.

This makes it possible to use python modules in MATLAB. Without any other changes, just prefix ‘py’ before the python library name you want to use. Let us use the Python calendar module as an example.

py.calendar.isleap(2016);
py.calendar.isleap(2017);

OUTPUT

ans =1
ans = 0

To run our own function, we can create a file in our current MATLAB working directory. Let’s say we created a file called ‘hello.py’ that contains these two lines:

def world():
    return 'hello world';

#  In MATLAB, if we run the following command we get following output

py.hello.world();

OUTPUT

Hello world!

Updated on: 27-Sep-2019

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements