Main Content

MATLAB 数据传递给 Python

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

将标量值传递给 Python

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

生成的 Python py. 类型

示例

double(实数)
single(实数)

float

在 MATLAB 中使用 Python 数值变量

double(复数)
single(复数)

complex

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

    (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 no properties.

    [None, 'Value']

logical

bool

 

dictionary

dict

在 MATLAB 中使用 Python dict 变量

struct

dict

在 MATLAB 中使用 Python dict 变量
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

将向量传递给 Python

MATLAB 输入参量类型 -
1 ×N 向量

生成的 Python 类型

double(实数)

array.array('d')

single(实数)

array.array('f')

int8(实数)

array.array('b')

uint8(实数)

array.array('B')

int16(实数)

array.array('h')

uint16(实数)

array.array('H')

int32(实数)

array.array('i')

uint32(实数)

array.array('I')

int64(实数)

array.array('q')

uint64(实数)

array.array('Q')

double(复数)
single(复数)

memoryview

logical

memoryview

char 向量
string 标量

str

cell 向量

tuple

将矩阵和多维数组传递给 Python

Python 语言提供访问内存缓冲区(如存储在 MATLAB 数组中的数据)的协议。MATLAB 为 MATLAB 数组实现此 Python 缓冲区协议,以便直接从 Python 代码中读取 MATLAB 数组,从而在与 MATLAB 相同的进程中运行,而无需复制数据。

许多 Python 函数直接从 Python 使用 MATLAB 数组,而不将其转换为原生 Python 类型。某些函数可能需要特定类型,例如 numpy.ndarray,或可能会修改数组中的数据。这些函数可能接受 MATLAB 数组并将数据复制到所需的类型中。其他函数则不然,如果您未传递所需的类型,可能就会显示错误。要将数据传递给这些函数,请首先从 MATLAB 数据创建所需的 Python 类型,然后将其传递给 Python 函数。例如,要创建数组 p 以传递给需要 numpy.array 类型数据的 Python 函数,请键入:

p = py.numpy.array(magic(3))
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.

在 Python 中不支持 MATLAB 稀疏数组。请参阅 Unsupported MATLAB Types

参量错误故障排除

如果 Python 函数需要特定的 Python 多维数组类型,例如 numpy.ndarray,MATLAB 将显示消息,并提示应该如何继续。如果问题产生的原因有可能是将矩阵或多维数组作为参量传递,请执行以下操作。

  1. 查阅 Python 函数的文档,找出参量需要的类型。

  2. 在 MATLAB 中创建该类型的 Python 对象,并将其传递给 Python 函数。

例如,假设以下代码返回错误。

a = [1 2; 3 4];
py.pyfunc(a)

如果 pyfunc 的文档指定需要的类型为 numpy.ndarray,请尝试进行以下转换:

py.pyfunc(numpy.ndarray(a))

如果错误仍然存在,请通过查看 Python 异常中的其他信息来确定根本原因。

不支持的 MATLAB 类型

Python 不支持下列 MATLAB 类型。

  • 多维 charcell 数组

  • 稀疏数组

  • struct 数组

  • categorical 类型

  • containers.Map 类型

  • MATLAB 对象

  • matlab.metadata.Class (py.class)

相关示例

详细信息