Call Python function from MATLAB
Introduction
This document provides a comprehensive guide on how to call a function from a Python module within a MATLAB script. It assumes that MATLAB and Python are already installed, along with NumPy in the provided example.
Instructions
Consider the following directory structure:
our_module/ |- our_script.py matlab_scripts/ |- matlab_script.m
Create a Python script our_module/our_script.py with the following content:
import numpy def our_function(text): print('%s %f' % (text, numpy.nan))
This script defines a function that prints a string followed by NaN (not-a-number).
In MATLAB, navigate to the directory containing the Python module (our_module).
Call the Python function using the following statement:
py.our_module.our_script.our_function('Hello')
This should print the expected output:
Hello nan
However, if you create a MATLAB script matlab_script.m in the matlab_scripts directory with the same statement, you will encounter an error:
Undefined variable "py" or class "py.our_module.our_script.our_function". Error in matlab_script (line 1) py.our_module.our_script.our_function('Hello')
To resolve this error, add the base directory to Python's search path using the following code:
[own_path, ~, ~] = fileparts(mfilename('fullpath')); module_path = fullfile(own_path, '..'); python_path = py.sys.path; if count(python_path, module_path) == 0 insert(python_path, int32(0), module_path); end py.our_module.our_script.our_function('Hello')
This code retrieves the Python module's location, finds its base path, accesses the Python search path, checks if the base path is included, and inserts it if not.
Running the corrected script will now produce the expected output.
For more information, refer to the following resources: