Skip to main content
 首页 » 编程设计

python之R/Python/Julia 中 Matlab 的类型转换函数的等价物是什么

2025年05月04日10del

R 中 Matlab 的 typecast 函数的等价物是什么?在 Python 中?在 Julia ?此处给出了 Matlab 的类型转换函数的描述:typecast

例子,在 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 

谢谢

请注意:我不是在寻找与 Matlab 的 cast 函数等效的 R/Python/Julia(例如,我不是在寻找 as.integer,as.character in 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