Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

处理从 Python 函数返回到的数据

自动将 Python 类型转换为 MATLAB 类型

MATLAB® 自动将从 Python® 函数返回的下列数据类型转换为 MATLAB 类型。要转换其他类型,请参阅将 Python 类型显式转换为 MATLAB 类型

Python 返回类型,如 Python 中所显示

生成的 MATLAB 类型 - 标量

float

double

complex

复数 double

bool

logical

datetime

datetime

Python 类型显式转换为 MATLAB 类型

如果 Python 函数的输出实现 Python 缓冲区协议(如 numpy.ndarray)并且是数值或逻辑值,则 MATLAB 显示:

  • 实际的 Python 类型

  • 底层数据

  • 对应的 MATLAB 转换函数。使用此函数可将 Python 对象完全转换为 MATLAB 数组。

使用下列 MATLAB 函数将 Python 数据类型转换为 MATLAB 类型。

Python 返回类型或协议,如在 MATLAB 中所显示

MATLAB 转换函数

示例

py.str

string
char

在 MATLAB 中使用 Python str 变量

使用 __str__ 方法的对象

char

py.help('datetime.date.__str__')
Help on wrapper_descriptor in datetime.date:

datetime.date.__str__ = __str__(self, /)
    Return str(self).
d = py.datetime.date(...
    int32(2020),int32(3),int32(4));
char(d)
ans = '2020-3-04'

py.int
py.long
py.float
py.bool

数值函数:
double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64

 
logical

py.bytes

uint8

 

py.array.array
py.numpy.ndarray
py.memoryview

您可以将任何格式的 py.array.arraypy.memoryview 对象转换为所需的 MATLAB 类型。

数值函数:
double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64

在 MATLAB 中使用 Python 数值变量,例如,在 MATLAB 中使用 Python 整数数组类型。

py.listpy.tuple

double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64
logical
string
cell

在 MATLAB 中使用 Python list 变量
在 MATLAB 中使用 Python tuple 变量

有关详细信息,请参阅Error Converting Elements of list or tuple

映射协议;例如,py.dict

struct

在 MATLAB 中使用 Python dict 变量

py.datetime.datetime

datetime

dt = py.numpy.arange('2022-12-30', ...
    '2023-01-10',dtype='datetime64[D]');

py.datetime.timedelta

duration

td = py.numpy.array([1,2,3,4], ...
    dtype='timedelta64[h]');

例如,Python 函数返回此数组 p

p = 

  Python ndarray:

     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.

您可以通过键入以下内容将其转换为 MATLAB 矩阵 P

P = double(p)
P = 3×3    
     8     1     6
     3     5     7
     4     9     2

如果需要 p 的 Python 属性的特定信息,请键入:

details(p)
    py.numpy.ndarray handle with properties:

           T: [1×1 py.numpy.ndarray]
        base: [1×1 py.NoneType]
      ctypes: [1×1 py.numpy.core._internal._ctypes]
        data: [1×3 py.memoryview]
       dtype: [1×1 py.numpy.dtype[float64]]
       flags: [1×1 py.numpy.flagsobj]
        flat: [1×1 py.numpy.flatiter]
        imag: [1×1 py.numpy.ndarray]
    itemsize: [1×1 py.int]
      nbytes: [1×1 py.int]
        ndim: [1×1 py.int]
        real: [1×1 py.numpy.ndarray]
       shape: [1×2 py.tuple]
        size: [1×1 py.int]
     strides: [1×2 py.tuple]

  Methods, Events, Superclasses

如果 Python 模块在其 __doc__ 特性中提供内容,MATLAB 将链接到该信息。

相关示例

详细信息