Call Python Function from MATLAB



MATLAB has a built-in feature called Python integration that allows you to call Python functions directly from your MATLAB code. You don't need to install any extra tools or software as long as Python is already installed on your system; MATLAB can work with it.

With Python integration, you can call Python functions, use Python libraries, and interact with Python objects right inside MATLAB. To do this, simply use the py. prefix before the name of the Python function or module.

To make this work smoothly, make sure your Python environment is properly set up. Also, the Python function you are trying to call should either be in your current working folder or part of an installed Python module that MATLAB can access.

Using MATLAB's Python Interface

MATLAB makes it really easy to work with Python code. You can call any Python function directly from MATLAB by just adding py. before the module or function name. It is almost like calling a regular MATLAB function. The best part is, MATLAB handles conversion of data types automatically in most cases.

Syntax

The basic syntax to call a Python function from MATLAB is -

result = py.module_name.function_name(arguments)

In this syntax,

  • module_name is the name of the Python module (e.g., math)
  • function_name is the Python function you want to call (e.g., sqrt)
  • arguments are the inputs you want to pass to the function.

Return Value

When you call a Python function, MATLAB returns a Python object. If you want to work with it like a normal MATLAB variable, you can convert it using functions like double() for numbers, char() for strings, or cell() for lists.

Example

Let us try a simple example. We will call Python's math.sqrt() function to find the square root of a number "16" from inside MATLAB -

% Ensure Python is configured
pyenv('Version', '3.8');

% Call Python's math.sqrt() function
result = py.math.sqrt(16);

% Convert the result to a MATLAB double
sqrt_result = double(result);

% Display the result
disp(sqrt_result)

We get the following output ?

4

Calling Custom Python Functions from MATLAB

In addition to calling built-in Python functions, you can also call custom Python functions that you define. To do so, you need to make sure the Python script containing your function is accessible to MATLAB.

You can store the Python script in a directory that is in Python's search path, or you can use the py.importlib.import_module() function to import the script manually.

Example

In this example, we will create a custom Python function called multiply(), store it in a Python script, and call it from MATLAB -

# multiply.py
def multiply(a, b):
   return a * b

Now, let us call this Python function from MATLAB -

% Import the custom Python function
py.importlib.import_module('multiply');

% Call the multiply function
result = py.multiply.multiply(4, 5);

% Convert the result to a MATLAB double
multiply_result = double(result);

% Display the result
disp(multiply_result)

We get the following output ?

20

Managing Python File Paths in MATLAB

If your Python file is not in the same folder as your MATLAB script, MATLAB might not be able to find it. To fix this, you can add the folder containing your Python code to Python's system path.

You can do this using py.sys.path.append() method. This tells MATLAB where to look for your custom Python modules.

Example

Let us say you have a Python file named myfunctions.py saved in this folder -

C:\Users\MyName\Documents\PythonCode

And inside that file, you have a function like this -

# myfunctions.py
def square(x):
   return x * x

Now, to call this function from MATLAB, you can do the following -

% Add the folder to Python's system path
py.sys.path.append('C:\Users\MyName\Documents\PythonCode');

% Call the square function from myfunctions.py
result = py.myfunctions.square(7);

% Convert the result to a MATLAB double
disp(double(result))

So here, MATLAB successfully found your custom Python file, called the square() function, and printed the result. This method is helpful anytime you are working with your own Python code stored in different folders -

49

Using Python Libraries in MATLAB

MATLAB allows you to call Python libraries such as NumPy, Pandas, and others directly from your scripts.

Example

This example demonstrates how to call a function from the NumPy library in MATLAB -

arr = py.numpy.array([1, 2, 3, 4]);

% Convert the result to a MATLAB array
matlab_array = double(arr);

disp(matlab_array)

We get the following output -

1   2   3   4

Handling Python Data in MATLAB

When you use Python functions in MATLAB, the data returned might be in Python format. To work with this data in MATLAB, you need to convert it explicitly into MATLAB types using simple conversions -

  • double(obj): Converts Python numbers to MATLAB numbers
  • char(obj): Converts Python strings to MATLAB character arrays
  • cell(obj): Converts Python lists or tuples to MATLAB cell arrays

Always convert Python data before using it in your MATLAB calculations to avoid errors.

Example

Following is an example that shows how to call a Python function from MATLAB that returns a string -

Python function:

def welcome(name): 
   return f"Welcome, {name}!" 

MATLAB code to call the function:

msg = py.myfunctions.welcome('Ria'); 
disp(char(msg))

The Python function returns a greeting string. When calling it from MATLAB, the result is in Python string format, so we use char() function to convert it into a MATLAB string for display -

Welcome, Ria!

Handling Python Errors in MATLAB

When you run Python code from MATLAB, you may come across certain errors. The common ones are -

  • ModuleNotFoundError: Happens if MATLAB can't find the Python file or module.
  • TypeError: Occurs if you pass the wrong type or number of inputs to the function.
  • AttributeError: Raised if the function or method you are trying to use doesn't exist in the Python module.

You can use MATLAB's try...catch block to catch these errors and prevent your code from crashing. It also lets you show a custom error message.

Example

In this case, MATLAB tries to call a Python function that doesn't exist. Instead of throwing an error that stops the program, the catch block catches it and displays a friendly message -

try
   result = py.myfunctions.nonexistentFunc(10);
catch ME
   disp("Error: " + ME.message)
end

Following is the message displayed -

Error: No appropriate method, property, or field 'nonexistentFunc' for class 'py.myfunctions'.

Using Python Environments in MATLAB

MATLAB can work with different versions of Python, and it is important to make sure it is using the correct one, especially if you have more than one Python installation on your system.

Check the current Python setup

This command shows which Python version MATLAB is currently using -

pyenv

Set a specific Python version

If you want MATLAB to use a different Python version, set the full path to the Python executable like this -

pyenv('Version', 'C:\Path\To\python.exe')

You should run this before calling any Python functions. Restart MATLAB if you have already used Python in your session.

Updated on: 2025-05-14T15:34:50+05:30

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements