mar*_*yer 1 python matlab numpy
我试图将Matlab代码转换为Python,但是当我在数组中添加零时,我收到一个错误.
Matlab代码:
N_bits=1e5;
a1=[0,1];
bits=a1(ceil(length(a1)*rand(1,N_bits)));
bits=[0 0 0 0 0 0 0 0 bits];
Run Code Online (Sandbox Code Playgroud)
Python代码:
a1=array([0,0,1])
N_bits=1e2
a2=arange(0,2,1)
## Transmitter ##
bits1=ceil(len(a2)*rand(N_bits))
bits=a1[array(bits1,dtype=int)]
bits=array([0,0,0,0,0,0,0,0, bits])
Run Code Online (Sandbox Code Playgroud)
我在最后一行收到错误:
Error: bits=array([0,0,0,0,0,0,0,0, bits]) ValueError: setting an array element with a sequence.
您想要使用数组加入列表,请尝试
bits=concatenate(([0,0,0,0,0,0,0,0], bits))
Run Code Online (Sandbox Code Playgroud)
哪里concatenate()是numpy.concatenate().您也可以使用zeros(8, dtype=int)代替零列表(请参阅参考资料numpy.zeros()).
与Matlab不同,[0,0,0,0,0,0,0,0, bits]Python中的某些内容会创建一个列表,其中初始零后跟嵌入式列表.
Matlab的:
>> x = [1,2,3]
x =
     1     2     3
>> [0,0,x]
ans =
     0     0     1     2     3
Run Code Online (Sandbox Code Playgroud)
蟒蛇:
>>> x = [1,2,3]
>>>
>>> [0,0,x]
[0, 0, [1, 2, 3]]
>>> 
>>> [0,0] + x
[0, 0, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)