【问题标题】:"Error: setting an array element with a sequence"“错误:使用序列设置数组元素”
【发布时间】:2013-08-14 20:11:30
【问题描述】:

我正在尝试将 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];

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])

最后一行出现错误:

错误: 位=数组([0,0,0,0,0,0,0,0,位]) ValueError:使用序列设置数组元素。

【问题讨论】:

  • 它之前的行应该引发异常,因为您没有定义 a1..

标签: python matlab numpy


【解决方案1】:

你想用数组加入列表,所以试试

bits=concatenate(([0,0,0,0,0,0,0,0], bits))

其中concatenate()numpy.concatenate()。您还可以使用zeros(8, dtype=int) 代替零列表(请参阅numpy.zeros())。

与 Matlab 不同,Python 中的 [0,0,0,0,0,0,0,0, bits] 之类的东西会创建一个列表,其中初始零后跟 嵌入 列表。

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]

【讨论】:

  • 根据“位”的大小,您可能需要预先分配一个适当大小的数组,然后像这样填充它:bits = np.zeros(8 + N_bits, dtype='uint8'); bits[8:] = ...
  • @arshajii 不,它不起作用它说 bits=array([0,0,0,0,0,0,0,0]+bits) ValueError: 操作数不能与形状一起广播(8) (100)
  • numpy 数组重载 + 运算符以表示元素相加。要连接,请使用numpy.concatenate((array1, array2, ...))
  • @StevenRumbalski Ack,当然。对我来说一定是咖啡点。
猜你喜欢
  • 2018-08-15
  • 2016-10-30
  • 2018-09-01
  • 2016-01-01
  • 2015-08-10
  • 2018-04-09
  • 1970-01-01
  • 2018-11-10
相关资源
最近更新 更多