[英]Equivalent Python function for MATLAB typecast function
[英]what is the equivalent of Matlab's typecast function in R / Python / Julia
R中Matlab的typecast
函數等效於什么? 在Python中? 在朱莉婭? Matlab的類型轉換功能的描述在此處給出: 類型轉換
示例,在Matlab中
X = uint32([1 255 256])
X =
1 255 256
Y = typecast(X, 'uint8') # little endian
Y =
1 0 0 0 255 0 0 0 0 1 0 0
謝謝
請注意:我不是在尋找R / Python的/朱莉婭相當於Matlab的的cast
功能(例如,我不是在尋找as.integer
, as.character
在R)
編輯:
感謝您對Julia / R / Python的回答。 StackOverflow允許我選擇一個答案,但是我投票贊成所有答案。
在Julia中,您需要重新解釋 :
julia> X = Uint32[1,255,256]
3-element Array{Uint32,1}:
0x00000001
0x000000ff
0x00000100
julia> Y = reinterpret(Uint8,X)
12-element Array{Uint8,1}:
0x01
0x00
0x00
0x00
0xff
0x00
0x00
0x00
0x00
0x01
0x00
0x00
但是請注意,對於矩陣,即使第一個維度為單例,您也需要指定結果維度(因為要4x3還是1x12數組是模棱兩可的):
julia> X = Uint32[1 255 256]
1x3 Array{Uint32,2}:
0x00000001 0x000000ff 0x00000100
julia> Y = reinterpret(Uint8,X) # This won't work
ERROR: result shape not specified
julia> Y = reinterpret(Uint8,X,(1,12))
1x12 Array{Uint8,2}:
0x01 0x00 0x00 0x00 0xff 0x00 0x00 0x00 0x00 0x01 0x00 0x00
在R中,您可以將對象寫入原始二進制連接,並獲取字節向量。 這將使您等效於uint8
輸出示例:
> X=c(1,255,256)
> mode(X)
[1] "numeric"
這里重要的是存儲模式,而不是模式。 因此,我們將其設置為整數-相當於uint32,即每個整數4個字節:
> storage.mode(X)
[1] "double"
> storage.mode(X)="integer"
現在我們可以使用writeBin
。 第二個參數是任意原始向量,因此我們創建一個長度為零的臨時對象。 我們只關心返回值:
> Xraw = writeBin(X,raw(0))
> Xraw
[1] 01 00 00 00 ff 00 00 00 00 01 00 00
使用readBin
進行相反的操作:
> readBin(Xraw,"int",n=3)
[1] 1 255 256
將前8個字節解壓縮為一個double:
> Xdoub = readBin(Xraw,"double",n=1)
> Xdoub
[1] 5.411089e-312
顯然是胡扯的值。 但讓我們檢查其相同的前8個字節:
> writeBin(Xdoub,raw(0))
[1] 01 00 00 00 ff 00 00 00
R並不是真正具有所有的C級類型,因此,如果您需要任何內容,都可以從原始字節構建它,也可以編寫一些C代碼以與R函數鏈接。
>>> import numpy as np
>>> x = np.array([1,255,256], dtype=np.int32)
>>> y = x.view(np.uint8)
(您可以類似地更改x
本身的類型: x.dtype = np.uint8
)。
輸出:
>>> x
array([ 1, 255, 256])
>>> y
array([ 1, 0, 0, 0, 255, 0, 0, 0, 0, 1, 0, 0], dtype=uint8)
請注意, y
是x
的就地重新解釋視圖 ,因此y
任何更改都將反映在x
:
>>> y[:] = 255
>>> x
array([-1, -1, -1])
這是等效的MATLAB輸出:
>> x = int32([1,2,3])
x =
1 2 3
>> y = typecast(x, 'uint8')
y =
1 0 0 0 2 0 0 0 3 0 0 0
>> y(:) = 255
y =
255 255 255 255 255 255 255 255 255 255 255 255
>> xx = typecast(y, 'int32')
xx =
-1 -1 -1
如果要進行類型轉換而不在MATLAB中創建深層副本,請參見typecastx
MEX函數(使用未記錄的功能來創建共享數據副本)。
注意MATLAB使用飽和算法 ,取消鏈接具有模塊化算法的 Python:
# wraps around the other end
>>> np.array(257, dtype=np.uint8)
array(1, dtype=uint8)
% saturates at the maximum
>> uint8(257)
ans =
255
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.