关于python:MATLAB使用Python数值和字符变量

6次阅读

共计 1568 个字符,预计需要花费 4 分钟才能阅读完成。

在 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 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(P)
谬误应用 sum
数据类型有效。第一个参数必须为数值或逻辑值。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

以上就是本次分享的全部内容,当初想要学习编程的小伙伴欢送关注 Python 技术大本营,获取更多技能与教程。

正文完
 0