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 mymod.py 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 mymod.py.

# mymod.py
"""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
    insert(py.sys.path,int32(0),'');
end

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

def search(words):

Read the function help in the mymod.py 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 = py.mymod.search(N)
names = 

  Python list with no properties.

    ['Johnson']

The function returns a py.list value.

The original input, N is unchanged.

N
N = 

  Python list with no properties.

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

Related Topics