问题
I am trying to convert Matlab code into Python, but I'm receiving an error when I append zeros in my array.
Matlab Code:
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];
Python Code:
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])
I get an error on the last line:
Error: bits=array([0,0,0,0,0,0,0,0, bits]) ValueError: setting an array element with a sequence.
回答1:
You want to join the list with the array, so try
bits=concatenate(([0,0,0,0,0,0,0,0], bits))
where concatenate()
is numpy.concatenate(). You can also use zeros(8, dtype=int)
in place of the list of zeros (see numpy.zeros()).
Unlike in Matlab, something like [0,0,0,0,0,0,0,0, bits]
in Python creates a list with the initial zeros follows by an embedded list.
Matlab:
>> x = [1,2,3]
x =
1 2 3
>> [0,0,x]
ans =
0 0 1 2 3
Python:
>>> x = [1,2,3]
>>>
>>> [0,0,x]
[0, 0, [1, 2, 3]]
>>>
>>> [0,0] + x
[0, 0, 1, 2, 3]
来源:https://stackoverflow.com/questions/18241359/error-setting-an-array-element-with-a-sequence