Python 中 Matlab 的 typecast
函数相当于什么? 在朱莉娅?这里给出了 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
在 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 个字节解压缩为双精度:
> 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 函数链接。
Python/Numpy:
>>> 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
如果您希望在不创建深层副本的情况下进行类型转换,请参阅typecastx
MEX 函数(它使用未记录的功能来创建共享数据副本)。
请注意,MATLAB使用饱和算法,取消链接具有模块化算法的Python:
Python/Numpy
# wraps around the other end
>>> np.array(257, dtype=np.uint8)
array(1, dtype=uint8)
马特实验室
% saturates at the maximum
>> uint8(257)
ans =
255