Main Content

在 MATLAB 中使用 Python 数值变量

此示例说明如何在 MATLAB® 中使用 Python® 数值类型。

在 MATLAB 中使用 Python 数值类型

当调用接受数值输入参量的 Python 函数时,MATLAB 会将双精度值转换为最适合在 Python 语言中表示该数据的类型。例如,要调用 Python math 模块中的三角函数,请传递 MATLAB 双精度值。

pynum = py.math.radians(90)
pynum = 1.5708

对于返回 Python float 类型的函数,MATLAB 会自动将该类型转换为双精度类型。

class(pynum)
ans = 
'double'

对于返回整数类型的 Python 函数,MATLAB 会自动将该类型转换为 int64。例如,bit_length 函数返回将二进制整数表示为 int 值所需的位数。

py.int(intmax).bit_length
ans = int64
    31

用数值 iterable 参量调用 Python 方法

Python math.fsum 函数对 iterable 输入参量中的浮点值求和。您可以将 MATLAB 向量传递给此函数。例如,打开 MATLAB patients.mat 数据文件并读取数值数组 Height

load patients.mat
class(Height)
ans = 
'double'
size(Height)
ans = 1×2

   100     1

当您将此参量传递给 Python 时,MATLAB 自动将数值转换为 Python 数值且 Python 会对向量值进行迭代。

py.math.fsum(Height)
ans = 6707

在 MATLAB 中使用 Python array 类型

假设您有一个 Python 函数,它返回以下双精度类型的 Python array.array

P = py.array.array('d', 1:5)
P = 
  Python array with properties:

    itemsize: 8
    typecode: [1×1 py.str]

    array('d', [1.0, 2.0, 3.0, 4.0, 5.0])

要将 P 传递给 MATLAB 函数 sum,请将 P 转换为双精度类型的 MATLAB 数组。

sum(double(P))
ans = 15

在 MATLAB 中使用 Python 整数 array 类型

假设您有以下 Python 数组。对该数组调用 Python reverse 函数,然后将结果转换为 MATLAB 数组。

arr = py.array.array('i',[int32(5),int32(1),int32(-5)])
arr = 
  Python array with properties:

    itemsize: 4
    typecode: [1×1 py.str]

    array('i', [5, 1, -5])

arr.reverse
A = int32(arr)
A = 1×3 int32 row vector

   -5    1    5

默认数值类型

默认情况下,MATLAB 中的数值是 double 类型。默认情况下,Python 中的数值(没有小数部分)是整数类型。这种差异会导致在将数值传递给 Python 函数时出现混淆。

例如,当您将下列 MATLAB 数值传递给 Python datetime 函数时,Python 会将它们读取为 float 类型并显示错误:

d = py.datetime.date(2014,12,31)

Python Error: TypeError: integer argument expected, got float

要更正该错误,请将每个数值显式转换为整数类型:

d = py.datetime.date(int32(2014),int32(12),int32(31))
d = 
  Python date with properties:

      day: 31
    month: 12
     year: 2014

    2014-12-31

为什么我在显示数值时会看到属性?

MATLAB 将所有 Python 类型显示为对象,其中包括对象属性列表。对于数值类型,MATLAB 在最后一行显示预期的输出值。

py.int(5)
ans = 
  Python int with properties:

    denominator: 1
           imag: 0
      numerator: 5
           real: 5

    5