主要内容

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

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

MATLAB® 自动将从 Python® 函数返回的下列数据类型转换为 MATLAB 类型。

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

生成的 MATLAB 类型 - 标量

float

double

complex

复数 double

bool

logical

datetime

datetime

此外,当包含 Python 字符串对象的 Python 字典或 Python Pandas DataFrame 从 Python 返回到 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 数值变量

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 或实现映射协议的其他对象

dictionary
struct

在 MATLAB 中使用 Python 字典
py.pandas.DataFrame

table
timetable

在 MATLAB 中使用 Python Pandas DataFrame

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 函数的输出具有实现 Python 缓冲区协议的类型(如 numpy.ndarray),则 MATLAB 显示:

  • 实际的 Python 类型

  • 底层数据

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

例如,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.

使用建议的转换函数将 p 转换为 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 将链接到该信息。

另请参阅

主题