主要内容

MATLABMATLABPython 之间传递数据

当您在 MATLAB® 中调用 Python® 函数时,Python 接口将 MATLAB 输入数据转换为最适合用 Python 语言表达该数据的类型。Python 接口还会将一些返回的 Python 数据转换为 MATLAB 数据类型。

将数据从 MATLAB 传递到 Python

当您将数据从 MATLAB 传递给 Python 时,生成的 Python 类型取决于 MATLAB 数据是标量值还是数组。

将标量值从 MATLAB 传递给 Python

在 MATLAB 中,当您将标量值作为输入传递给 Python 函数时,Python 接口会自动将数据转换为等效的 Python 数据类型。

MATLAB 输入类型
(仅适用于标量值)

生成的 Python 数据类型

示例

double(实数)
single(实数)

float(默认值)或 int

在 MATLAB 中使用 Python 数值变量

默认情况下,Python 接口将类型 doublesingle 转换为 Python float。然而,对于基于 Python 类型提示的整数值,Python 接口可以将类型 doublesingle 转换为 Python int

double(复数)
single(复数)

complex

z = complex(1,2);
py.cmath.polar(z)
ans = 
  Python tuple with values:

    (2.23606797749979, 1.1071487177940904)

int8
uint8
int16
uint16
int32
uint32
int64
uint64

int

在 MATLAB 中使用 Python 数值变量

NaN

float("nan")

n = NaN;
py.float(n)
ans = 

  Python float with properties:

    imag: 0
    real: NaN

    nan

Inf

float("inf")

i = Inf;
py.float(i)
ans = 

  Python float with properties:

    imag: 0
    real: Inf

    inf

string 标量
char 向量

str

在 MATLAB 中使用 Python str 变量

string
string(missing) 中的 <missing>

str 中的 None

s = string(missing);
py.str(s)
ans = 

  Python str with no properties.

    None

logical

bool

b = true;
py.type(b)
ans = 

  Python type with no properties.

    <class 'bool'>

dictionary
struct

dict

在 MATLAB 中使用 Python 字典

table
timetable

pandas.DataFrame在 MATLAB 中使用 Python Pandas DataFrame
datetime

datetime.datetime

Use Python Datetime Types in MATLAB
duration

datetime.timedelta

Use Python Duration Types in MATLAB

Python 对象 - py.type

type

-

函数句柄 @py.module.function(仅限于指向 Python 函数的函数句柄)

module.function

Pass Python Function to Python map Function

将数组数据从 MATLAB 传递给 Python

在 MATLAB 中,当您将 MATLAB 数组作为输入传递给 Python 函数且 NumPy 模块在 Python 环境中可用时,Python 接口会自动将数组转换为 Python NumPy 数组。如果在将 MATLAB 数组作为输入传递给 Python 函数时 NumPy 模块不可用,则 Python 接口将向量输入视为矩阵输入进行处理 - Python 接口将这些输入转换为 Python memoryview 对象。(自 R2025a 起)

在 R2025a 之前的版本中: 当您将 MATLAB 向量(无论是否具有 NumPy 包)传递给 Python 函数时,Python 接口将该向量转换为 Python array.array 对象。

MATLAB 输入数组类型(仅适用于数组数据)

生成的 Python 数据类型(使用 NumPy)

double(实数)

numpy.array(dtype=np.float64)

single(实数)

numpy.array(dtype=np.float32)

int8(实数)

numpy.array(dtype=np.int8)

uint8(实数)

numpy.array(dtype=np.uint8)

int16(实数)

numpy.array(dtype=np.int16)

uint16(实数)

numpy.array(dtype=np.uint16)

int32(实数)

numpy.array(dtype=np.int32)

uint32(实数)

numpy.array(dtype=np.uint32)

int64(实数)

numpy.array(dtype=np.int64)

uint64(实数)

numpy.array(dtype=np.uint64)

double(复数)

numpy.array(dtype=np.complex128)

single(复数)

numpy.array(dtype=np.complex64)

logical

numpy.array(dtype=np.bool)

char 向量

str

cell 向量

tuple

NM×1 string 向量

list

datetime 数组

numpy.datetime64 数组

duration 数组

numpy.timedelta64 数组

char 矩阵
cell 矩阵
M×N string 数组,其中 MN 都大于 1

无自动转换。

如果未安装 NumPy,并且将数值 MATLAB 数组传递给 Python,则 Python 接口会创建一个指向数组内容的 memoryview 对象。此 memoryview 对象实现 Python 缓冲区协议,并且不会复制数组。在此示例中,array.array 是基于由 MATLAB 数组创建的 memoryview 对象构造的。

mArr = [1,2,3];
pyArr = py.array.array('d',mArr);

MATLAB 类型显式转换为 Python 类型

尽管 Python 接口不会自动转换多维 MATLAB 字符串数据,但您可以显式将数据转换为 Python 数据类型。

MATLAB 类型

生成的 Python 类型

MATLAB 转换函数

字符串数组

NumPy StringDType 数组

pystringarray

不支持的 MATLAB 类型

Python 不支持下列 MATLAB 类型:

  • 稀疏数组

  • 非标量 struct 数组

  • categorical

  • containers.Map

  • MATLAB 对象

  • matlab.metadata.Class (py.class)

将数据从 Python 传递到 MATLAB

当您从 MATLAB 中调用 Python 函数时,这些函数可以返回任何数据类型的数据。根据 Python 函数返回的数据类型,Python 接口可能会自动将输出转换为 MATLAB 数据类型。如果 Python 接口不自动转换数据,则 Python 函数会返回 Python 数据类型的输出,然后您可以将其手动转换为 MATLAB 数据类型。

PythonMATLAB 返回标量值

当 Python 函数返回以下任一 Python 数据类型的标量值时,Python 接口会自动将该值转换为对应的 MATLAB 类型。

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

生成的 MATLAB 数据类型
(仅适用于标量值)

float

double

complex

复数 double

bool

logical

datetime

datetime

pandas.DataFrame 中的 str 对象
dict 中的 str 对象

string

Python 类型显式转换为 MATLAB 类型

当 Python 函数返回任何其他类型的数据时,Python 接口不会自动转换该数据。您可以使用以下 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, /) unbound datetime.date method
    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

double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64

在 MATLAB 中使用 Python 数值变量
py.bool

logical
double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64

x = py.bool(true);
double(x)
ans =

     1

py.bytes

uint8

b = py.bytes("MATLAB",'utf-8');
uint8(b)
ans =

  1×6 uint8 row vector

   77   65   84   76   65   66

py.array.array
py.memoryview

double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64

在 MATLAB 中使用 Python 数值变量

py.numpy.ndarray

double
single
int8
uint8
int16
uint16
int32
uint32
int64
uint64
string

将 Python ndarray 转换为 MATLAB 数组

py.list
py.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
py.numpy.datetime64

datetime

Use Python Datetime Types in MATLAB

py.datetime.timedelta
py.numpy.timedelta64

duration

Use Python Duration Types in MATLAB

不支持的 Python 类型

MATLAB 中不支持 Python enum 类型。

Python ndarray 转换为 MATLAB 数组

如果 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 矩阵 M

M = double(p)
M = 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 将链接到该信息。

另请参阅

主题