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_lengthans = int64 31用數值?iterable?參數調用 Python 方法
Python?math.fsum?函數對?iterable?輸入參數中的浮點值求和。例如,打開 MATLAB patients.mat?數據文件并讀取數值數組?Height。???????
load patients.matclass(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.reverseA = 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训练神经网络模型并导入sim