Main Content

Advanced Topics

UnderstandingPythonandMATLABimportCommands

Theimportstatement does not have the same functionality in MATLAB®as in Python®.

LoadPythonModule inMATLAB

Python code uses theimportstatement to load and make code accessible. MATLAB automatically loads Python when you typepy.in front of the module name and function name. This code shows how to call a functionwrapin Python moduletextwrap.

Python Code MATLAB Code
import textwrap pS1 = textwrap.wrap('This is a string')
S1 = py.textwrap.wrap('This is a string');

Caution

In MATLAB, do not type:

importpythonmodule

Never call:

import py.*

If you do, then MATLAB calls the Python function instead of the MATLAB function of the same name. This can cause unexpected behavior. If you type thisimportcommand, then you must call the MATLAB command:

clear import

Shorten Class or Function Names

The Pythonfrom...importstatement lets you reference a module without using the fully qualified name. In MATLAB, use theimportfunction. This code shows how to reference functionwrapin Python moduletextwrap. Sincewrapis not a MATLAB function, you can shorten the calling syntax using theimportfunction. After calling this command, you do not need to type the package (py) and module (textwrap) names.

Python Code MATLAB Code
import textwrap pS1 = textwrap.wrap('This is a string') from textwrap import wrap pS2 = wrap('another string')
S1 = py.textwrap.wrap('This is a string'); importpy.textwrap.wrapS2 = wrap('another string');
importmymodas mm
mm = py.importlib.import_module('mymod'); % Use mm as an alias to access functionality inmymod

Help forPythonFunctions

For a complete description of Python functionality, consult outside resources, in particular,https://www.python.org. There are different versions of the Python documentation, so be sure to refer to the version corresponding to the version on your system. Many examples in the MATLAB documentation refer to functions in the Python standard library.

To use functions in a third-party or user-defined Python module, refer to your vendor product documentation for information about how to install the module and for details about its functionality.

The MATLABpy.helpcommand displays the Python help found atwww.python.org/doc. Help for packages and classes can be extensive and might not be useful when displayed in the MATLAB command window.

  • Package

    py.help('textwrap')
  • Class

    py.help('textwrap.TextWrapper')
  • Method of a class

    py.help('textwrap.TextWrapper.wrap')
  • Function

    py.help('textwrap.fill')

If MATLAB displays an error message beginning withPython Error:, refer to your Python documentation for more information.

Note

Tab completion does not display available Python functionality.

You cannot use the interactive Python help — callingpy.helpwithout input arguments — in MATLAB.

CallPython方法MATLABName Conflict

If a Python method name is the name of a sealed method of a MATLAB base class or reserved function, then MATLAB renames the method. The new name starts with the letterxand changes the first letter of the original name to uppercase. For example, MATLAB renames the Python methodcattoxCat. For a list of reserved methods, seeMethods That Modify Default Behavior.

If a method name is a MATLAB keyword, then MATLAB callsmatlab.lang.makeValidNameto rename the method. For a list of keywords, seeiskeyword.

If a generated name is a duplicate name, then MATLAB renames the method usingmatlab.lang.makeUniqueStrings.

CallPythonevalFunction

This example shows how to evaluate the expressionx+yusing the Pythonevalcommand. Read the help foreval.

py.help('eval')
帮助模块__builtin内置函数eval__: eval(...) eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.

To evaluate an expression, pass a Pythondictvalue for theglobalsnamespace parameter.

Create a Pythondictvariable for thexandyvalues.

workspace = py.dict(pyargs('x',1,'y',6))
workspace = Python dict with no properties. {'y': 6.0, 'x': 1.0}

Evaluate the expression.

res = py.eval('x+y',workspace)
res = 7

Alternatively, to add two numbers without assigning variables, pass an emptydictvalue for theglobalsparameter.

res = py.eval('1+6',py.dict)
res = 7

Execute CallablePythonObject

To execute a callable Python object, use thefevalfunction. For example, if instanceobjof a Python class is callable, replace the Python syntaxobj(x1, ..., xn)with one of the following MATLAB statements:

feval(obj,x1, ..., xn)
obj(x1, ..., xn)

HowMATLABRepresentsPythonOperators

MATLAB supports the following overloaded operators.

Python Operator Symbol Python Methods MATLAB Methods
+(binary) __add__,__radd__ plus,+
-(binary) __sub__,__rsub__ minus,-
*(binary) __mul__,__rmul__ mtimes,*
/ __truediv__,__rtruediv__ mrdivide,/
== __eq__ eq,==
> __gt__ gt,>
< __lt__ lt,<
!= __ne__ ne,~=
>= __ge__ ge,>=
<= __le__ le,<=
-(unary) __neg__ uminus,-a
+(unary) __pos__ uplus,+a

The following Python operators are not supported.

Python Operator Symbol Python Method
% __mod__,__rmod__
** __pow__,__rpow__
<< __lshift__,__rlshift__
>> __rshift__,__rrshift__
& __and__,__rand__
^ __xor__,__rxor__
| __or__,__ror__
//(binary) __floordiv__,__rfloordiv__
+=(unary) __iadd__
-=(unary) __isub__
*=(unary) __imul__
/=(unary) __itruediv__
//=(unary) __ifloordiv__
%=(unary) __imod__
**=(unary) __ipow__
<<=(unary) __ilshift__
>>=(unary) __irshift__
&=(unary) __iand__
^=(unary) __ixor__
!=(unary) __ior__
~(unary) __invert__

See Also

|

Related Topics

External Websites