在 MATLAB 中使用 Python 数值变量
此示例说明如何在 MATLAB® 中使用 Python® 数值类型。
在 MATLAB 中使用 Python 数值类型
默认情况下,MATLAB 中的数值具有双精度类型。然而,在 Python 中,没有小数部分的数值默认为具有整数类型。为了解决当调用接受数值输入参量的 Python 函数时的转换错误,MATLAB 会将 double 值转换为最适合在 Python 语言中表示该数据的类型。
例如,要调用 Python math 模块中的三角函数,请传递 MATLAB double 值。
pynum = py.math.radians(90)
pynum = 1.5708
对于返回 Python float 类型的函数,MATLAB 会自动将该类型转换为 double。
class(pynum)
ans = 'double'
对于返回 Python int 类型的函数,MATLAB 会自动将该类型转换为 int。例如,bit_length 函数返回将二进制整数表示为 int 值所需的位数。
py.int(intmax).bit_length
ans =
Python int with properties:
denominator: [1×1 py.int]
imag: [1×1 py.int]
numerator: [1×1 py.int]
real: [1×1 py.int]
31
在将参量传递给 Python 函数之前,MATLAB 还会在将 MATLAB double 值转换为 Python int 时使用 Python 类型提示。(从 R2024b 开始提供)
例如,Python date 构造函数需要整数输入。当您将 MATLAB 数值传递给 datetime 模块中的 Python date 构造函数时,MATLAB 首先将 double 值转换为整数。
d = py.datetime.date(2014,12,31)
d =
Python date with properties:
day: [1×1 py.int]
month: [1×1 py.int]
year: [1×1 py.int]
2014-12-31
对于提供类型提示信息的用户编写的函数,也支持从 double 到 int 的转换。但是,MATLAB 中类型提示信息的使用是受限的。例如,不支持诸如 Python typing 模块之类的模块。MATLAB 也不支持来自桩件模块或包含桩件的模块的类型提示。此外,仅在没有精度损失的情况下,MATLAB 才会将 double 转换为 int。
用数值 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:
1 2 3 4 5
Use details function to view the properties of the Python object.
Use double function to convert to a MATLAB array.
要将 P 传递给 MATLAB 函数 sum,请将 P 转换为 double 类型的 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:
5 1 -5
Use details function to view the properties of the Python object.
Use int32 function to convert to a MATLAB array.
arr.reverse A = int32(arr)
A = 1×3 int32 row vector
-5 1 5
为什么我在显示数值时会看到属性?
MATLAB 将所有 Python 类型显示为对象,其中包括对象属性列表。对于数值类型,MATLAB 在最后一行显示预期的输出值。
py.int(5)
ans =
Python int with properties:
denominator: [1×1 py.int]
imag: [1×1 py.int]
numerator: [1×1 py.int]
real: [1×1 py.int]
5