This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Call User-Defined Python Module

This example shows how to call methods from the following Python® module. This module is used by examples in the documentation.

This example explains how to create the module in MATLAB®. If you create in a Python editor, be sure that the module is on the Python search path. This example also explains how to get help for calling the function, if you are not an experienced Python user.

Change your current folder to a writable folder.

Open a new file in MATLAB Editor.

Copy these commands and save the file as

"""Python module demonstrates passing MATLAB types to Python functions"""
def search(words):
    """Return list of words containing 'son'"""
    newlist = [w for w in words if 'son' in w]
    return newlist

def theend(words):
    """Append 'The End' to list of words"""
    words.append('The End')
    return words

From the MATLAB command prompt, add the current folder to the Python search path.

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

To learn how to call the function, read the function signature for the search function in the source file. The function takes one input argument, words.

def search(words):

Read the function help in the source file. According to the Python website documentation, help is in “a string literal that occurs as the first statement in a module, function, class, or method definition.” The help for search is:

"""Return list of words containing 'son'"""

The function returns a list.

Create an input argument, a list of names, in MATLAB.

N = py.list({'Jones','Johnson','James'})
N = 

  Python list with no properties.

    ['Jones', 'Johnson', 'James']

Call the search function. Type py. in front of the module name and function name.

names =
names = 

  Python list with no properties.


The function returns a py.list value.

The original input, N is unchanged.

N = 

  Python list with no properties.

    ['Jones', 'Johnson', 'James']

Related Topics