绘制位模式时连续出现两次错误



我正试图用下面的代码块绘制一个比特流:

但不幸的是,Python抛出了两个错误:

C:Usersbahadir.yalinAnaconda3libsite-packagesnumpycore_asarray.py:171: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  return array(a, dtype, copy=False, order=order, subok=True)
TypeError: float() argument must be a string or a number, not 'list'

return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

我该如何解决这个问题?有人能帮帮我吗?谢谢你抽出时间。。

import random as rand
import numpy as np
import math as m
import matplotlib.pyplot as plt
a = [round(rand.randint(0,1)) for x in range(20)]
#list object is not callable
pi = m.pi
signal = []
carrier = []
##t = list(range(1,10000))
t = np.arange(10000)
fc = 0.01
for i in range(20):
    if a[i] == 0:
        sig =-np.ones(10001)
    else:
        sig = np.ones(10001)
    c = np.cos(2 *pi *fc *t)
    carrier = [carrier, c]
    signal = [signal, sig]
plt.plot(signal)
plt.title('Org. Bit Sequence')

您的代码会产生锯齿状数组,因为您一直在分配signal = [signal, sig]carrier = [carrier, c],在这两种情况下,它们都不会附加到现有列表中,而是使两个元素的列表更深层次。

例如,在您的代码之后,carrier看起来像:

>>> carrier
[[[[[[[[[[[[[[[[[[[[[],
                    array([1.        , 0.99802673, 0.9921147 , ..., 0.98228725, 0.9921147, 0.99802673])],
...
]
>>> len(carrier)
2
>>> len(carrier[0])
2
>>> len(carrier[0][0])
2
# etc.

下面是一些生成两个(20, 10000)阵列signalcarrier的代码。我不确定这是你想要得到的形状,也不确定你到底想画什么。如果更多细节渗透进来,会调整这个答案。。。

n, m = 10_000, 20
fc = 0.01
sign = 2 * np.random.randint(0, 2, size=m) - 1
t = np.arange(n)
signal = sign[:, None] @ np.ones(n)[None, :]
carrier = np.ones((m, 1)) @ np.cos(2 * np.pi * fc * t)[None, :]

现在:

>>> carrier.shape
(20, 10000)
>>> signal.shape
(20, 10000)

首先,-np.ones()不工作,所以我用-1*np.ones()替换了它。其次,通过不使用append()或类似的方法,您将数组的副本保存为新元素,如下所示:

>>> [[],np.ones()] #something like this first loop
>>> [[[],np.ones()],np.ones()] #second loop
>>> [[[[],np.ones()],np.ones()], np.ones()] #etc for twenty loops

这就是我为了让它发挥作用所做的:

import numpy as np
import math as m
import matplotlib.pyplot as plt
import random as rand
a = [rand.randint(0,1) for x in range(20)]
#list object is not callable
pi = m.pi
signal = []
carrier = []
##t = list(range(1,10000))
t = np.arange(10000)
fc = 0.01
for i in range(20):
    if a[i] == 0:
        sig = -1*np.ones(10001)
    else:
        sig = np.ones(10001)
    c = np.cos(2 * pi * fc * t)
    carrier.append(c)
    signal.append(sig)

plt.plot(signal)
plt.title('Org. Bit Sequence')
plt.show()

最新更新