“Error: setting an array element with a sequence”

两盒软妹~` 提交于 2021-01-28 14:08:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!