目录
将数据传递给 Python
MATLAB 类型到 Python 类型的映射
当将 MATLAB® 数据作为参数传递给 Python® 时,MATLAB 会将数据转换为最适合在 Python 语言中表达该数据的类型。
MATLAB 输入参数类型 - | 生成的 Python |
---|---|
double | float |
复数 single | complex |
int8 | int |
uint32 | int |
NaN | float(nan) |
Inf | float(inf) |
string 标量 | str |
string 中的 <missing> 值 | None |
logical | bool |
结构体 | dict |
Python 对象 - py.type | type |
函数句柄 @py.module.function(仅限于指向 Python 函数的函数句柄) | module.function |
MATLAB 向量到 Python 的映射
MATLAB 输入参数类型 - | 生成的 Python 类型 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
包含大于 127 的值的 |
|
|
|
|
|
|
|
传递矩阵和多维数组
将实数数组或逻辑数组传递给 Python 函数时,MATLAB 会自动将数据转换为 Python memoryview 对象。如果 Python 函数的输出实现 Python 缓冲区协议并且是实数或逻辑值,MATLAB 将显示:
-
实际的 Python 类型
-
底层数据
-
对应的 MATLAB 转换函数。使用此函数可将Python对象完全转换为 MATLAB 数组。
例如,假设在模块pyModule中调用Python函数,该函数返回类型为pyType的变量并具有以下值:
p =
Python pyType:
8 1 6
3 5 7
4 9 2
Use details function to view the properties of the Python object.
Use double function to convert to a MATLAB array.
要将 p 转换为 MATLAB 矩阵 P,请键入:
P = double(p)
P = 3×3
8 1 6
3 5 7
4 9 2
如果需要 p 的 Python 属性的特定信息,请键入:
details(p)
py.pyModule.pyType handle with properties:
T: [1×1 py.pyModule.pyType]
base: [1×1 py.NoneType]
ctypes: [1×1 py.pyModule.core._internal._ctypes]
data: [1×3 py.memoryview]
dtype: [1×1 py.pyModule.dtype]
flags: [1×1 py.pyModule.flagsobj]
flat: [1×1 py.pyModule.flatiter]
imag: [1×1 py.pyModule.pyType]
itemsize: [1×1 py.int]
nbytes: [1×1 py.int]
ndim: [1×1 py.int]
real: [1×1 py.pyModule.pyType]
shape: [1×2 py.tuple]
size: [1×1 py.int]
strides: [1×2 py.tuple]
Methods, Events, Superclasses
如果 Python 模块在其 __doc__ 特性中提供内容,MATLAB 将链接到该信息。
使用 Python memoryview 对象允许 Python 读取 MATLAB 数据,而无需制作 MATLAB 数据副本。有关 memoryview 对象和缓冲区协议的信息,在 Our Documentation | Python.org 网站上搜索这些术语。
Python不支持 MATLAB 复数数组和稀疏数组。
参数错误故障排除
如果 Python 函数需要特定的 Python 多维数组类型,MATLAB 将显示消息,并提示应该如何继续。如果问题产生的原因有可能是将矩阵或多维数组作为参数传递,请执行以下操作。
-
查阅 Python 函数的文档,找出参数需要的类型。
-
在 MATLAB 中创建该类型的 Python 对象,并将其传递给 Python 函数。
例如,假设以下代码返回错误。
a = [1 2; 3 4];
py.pyfunc(a)
如果 pyfunc 的文档指定需要的类型为 pyType,请尝试进行以下转换:
py.pyfunc(pyType(a))
如果错误仍然存在,请通过查看 Python 异常中的其他信息来确定根本原因。