Advanced Topics
Understanding Python and MATLAB import Commands
The import statement does not have the same behavior in MATLAB® as in Python®. In Python, you must use the "import pythonmodule" statement
before you can access functions from pythonmodule. In MATLAB, to call a function functionname from
pythonmodule, type
py.pythonmodule.functionname.
In MATLAB, use the statement "import
py.pythonmodule.functionname" to eliminate the need to type py.pythonmodule. wherever you call the function in the
remainder of the code. However, only use import when
functionname is not the name of an existing MATLAB function.
Load Python Module in MATLAB
Python code uses the import statement to load and make
code accessible. MATLAB automatically loads Python when you type py. in front of the
module name and function name. This code shows how to call a function
wrap in Python module textwrap.
| Python Code | MATLAB Code |
|---|---|
| S1 = py.textwrap.wrap('This is a string');
|
Caution
In MATLAB, do not type:
import pythonmodule
or:
import py.*
If you do, then whenever there are MATLAB and Python functions with the same name, MATLAB calls the Python function. This can cause unexpected behavior.
If by mistake you type this import command, then you must call the
MATLAB command:
clear import
Shorten Class or Function Names
The Python
from...import statement lets you reference a module without using
the fully qualified name. In MATLAB, use the import function. This code shows
how to reference function wrap in Python module textwrap. Since there is no MATLAB function called wrap and hence no danger of name
collision, you can shorten the calling syntax using the import
function. After calling this command, you do not need to type the namespace
(py) and module (textwrap) names.
| Python Code | MATLAB Code |
|---|---|
| S1 = py.textwrap.wrap('This is a string'); import py.textwrap.wrap S2 = wrap('another string'); |
|
mm = py.importlib.import_module('mymod');
% Use mm as an alias
% to access functionality
% in mymod |
Help for Python Functions
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 MATLAB
py.help command displays the Python help found at www.python.org/doc. Help for modules and
classes can be extensive and might not be useful when displayed in the MATLAB command window.
Module
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 with Python 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 — calling py.help without input arguments — in MATLAB.
Call Python Method With MATLAB Name 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 letter
x and changes the first letter of the original name to uppercase.
For example, MATLAB renames the Python method cat to xCat. For a list of
reserved methods, see Methods That Modify Default Behavior.
If a method name is a MATLAB keyword, then MATLAB calls matlab.lang.makeValidName to rename the
method. For a list of keywords, see iskeyword.
If a generated name is a duplicate name, then MATLAB renames the method using matlab.lang.makeUniqueStrings.
Call Python eval Function
This example shows how to evaluate the expression x+y using the
Python
eval command. Read the help for eval.
py.help('eval')Help on built-in function eval in module __builtin__:
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 Python
dict value for the globals namespace
parameter.
Create a Python
dict variable for the x and y
values.
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 empty
dict value for the globals parameter.
res = py.eval('1+6',py.dict)res =
Python int with properties:
denominator: [1×1 py.int]
imag: [1×1 py.int]
numerator: [1×1 py.int]
real: [1×1 py.int]
7Execute Callable Python Object
To execute a callable Python object, use the feval function. For example, if instance obj of a Python class is callable, replace the Python syntax obj(x1, ..., xn) with one of the following MATLAB statements:
feval(obj,x1, ..., xn)
obj(x1, ..., xn)
How MATLAB Represents Python Operators
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__ |