Advanced Topics
UnderstandingPythonandMATLABimport
Commands
Theimport
statement does not have the same functionality in MATLAB®as in Python®.
LoadPythonModule inMATLAB
Python code uses theimport
statement 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 functionwrap
in 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 thisimport
command, then you must call the MATLAB command:
clear import
Shorten Class or Function Names
The Pythonfrom...import
statement lets you reference a module without using the fully qualified name. In MATLAB, use theimport
function. This code shows how to reference functionwrap
in Python moduletextwrap
. Sincewrap
is not a MATLAB function, you can shorten the calling syntax using theimport
function. 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.help
command 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.help
without 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 letterx
and changes the first letter of the original name to uppercase. For example, MATLAB renames the Python methodcat
toxCat
. For a list of reserved methods, seeMethods That Modify Default Behavior.
If a method name is a MATLAB keyword, then MATLAB callsmatlab.lang.makeValidName
to 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
.
CallPythoneval
Function
This example shows how to evaluate the expressionx+y
using the Pythoneval
command. 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 Pythondict
value for theglobals
namespace parameter.
Create a Pythondict
variable for thex
andy
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 emptydict
value for theglobals
parameter.
res = py.eval('1+6',py.dict)
res = 7
Execute CallablePythonObject
To execute a callable Python object, use thefeval
function. For example, if instanceobj
of 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__ |