我是 Matlab 用户,正在尝试转向 Python。我尝试用我之前在 Matlab 中用过的 Python 编写一个 de2bi 函数的最小示例(它将十进制转换为二进制作为 right-msb)。但是,我对 numpy 数组感到困惑。
Python代码:
import numpy as np
def de2bi(d, n)
d = np.array(d)
power = 2**np.arange(n)
d = d * np.ones((1,n))
b = np.floor((d%(2*power))/power)
return b
Python 输出:
>>> print(de2bi(13,8))
[[ 1. 0. 1. 1. 0. 0. 0. 0.]]
print(de2bi([13,15],8)) #This line fails
Matlab代码:
function b = d2b( d, n )
d = d(:);
power = ones(length(d), 1)*(2.^(0 : n-1));
d = d * ones(1, n);
b = floor(rem(d, 2*power)./power);
end
Matlab 输出:
>> d2b(13,8)
ans =
1 0 1 1 0 0 0 0
>> d2b([13,15],8)
ans =
1 0 1 1 0 0 0 0
1 1 1 1 0 0 0 0
Matlab 代码适用于整数输入和整数数组。但是 python 代码适用于整数输入,但对数组一直失败。如何在 Python 中自动管理整数和整数数组的操作?对不起,这可能是一个非常简单的问题,但我是 Python 的新手。
提前致谢。
请您参考如下方法:
您的问题在于乘法:d = d * np.ones((1,n))。 NumPy 尝试执行逐元素乘法,但由于维度不匹配(您的 ones 数组只有一行)而失败。但是,当 d 是标量时,NumPy 可以推断出您的意思是乘以标量,因此代码会运行。
您真正想要做的(据我了解)是将每个元素扩展为一个长度为 n 的行。一个可能的解决方案是创建一个中间数组来保存新值,因为数组的大小是不可更改的:
def d2b(d, n):
d = np.array(d)
d = np.reshape(d, (1, -1))
power = np.flipud(2**np.arange(n))
g = np.zeros((np.shape(d)[1], n))
for i, num in enumerate(d[0]):
g[i] = num * np.ones((1,n))
b = np.floor((g%(2*power))/power)
return b
