主要内容

MATLAB 数据传递给 Python

当您在 MATLAB® 中调用 Python® 函数时,MATLAB 中的 Python 接口将 MATLAB 数据转换为最适合用 Python 语言表达该数据的类型。有关在 MATLAB 中使用 Python 数据的信息,请参阅处理从 Python 函数返回到的数据

MATLAB 标量数据传递给 Python

在 MATLAB 中,当您将标量数据从 MATLAB 传递给 Python 函数时,Python 接口将数据转换为等效的 Python 数据类型。

MATLAB 输入参量类型 -
仅标量值

生成的 Python py. 类型

示例

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

int

-

uint32
int64
uint64

int

-

NaN

float("nan")

-

Inf

float("inf")

-

string 标量
char 向量

str

在 MATLAB 中使用 Python str 变量

string 中的 <missing>

None

py.list({string(missing),"Value"})
ans = 
  Python list with values:

    [None, 'Value']

logical

bool

-

dictionary

dict

在 MATLAB 中使用 Python 字典

struct

dict

在 MATLAB 中使用 Python 字典
tablepy.pandas.DataFrameUse Python Pandas DataFrames in MATLAB
timetablepy.pandas.DataFrameUse Python Pandas DataFrames in MATLAB
datetime

py.datetime.datetime

Use MATLAB Datetime Types with Python
duration

py.datetime.timedelta

Use MATLAB Duration Types with Python

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

datetime 数组

numpy.datetime64 数组

duration 数组

numpy.timedelta64 数组

char 矩阵
string 数组

不支持此转换。

Python 语言提供一种访问内存缓冲区(例如存储在 MATLAB 数组中的数据)的协议。如果未安装 NumPy,则 Python 接口为 MATLAB 数组实现此 Python 缓冲区协议,以便直接从 Python 代码中读取 MATLAB 数组,从而在与 MATLAB 相同的进程中运行,而无需复制数据。此数据缓冲区随后转换为 Python memoryview 对象。在此示例中,Python 接口在将 MATLAB 数组 marr 传递给 array.array 构造函数时将其转换为 memoryview 对象。

marr = [1,2,3];
pyarr = py.array.array('d',marr);

不支持的 MATLAB 类型

Python 不支持下列 MATLAB 类型。

  • 多维 charcell 数组

  • 稀疏数组

  • struct 数组

  • categorical

  • containers.Map

  • MATLAB 对象

  • matlab.metadata.Class (py.class)

另请参阅

主题