【问题标题】:ValueError: x and y must have same first dimension, but have shapes (512,) and (256,)ValueError:x 和 y 必须具有相同的第一维,但具有形状 (512,) 和 (256,)
【发布时间】:2020-04-13 15:10:55
【问题描述】:

我尝试使用 numpy 和 np.array 但失败了。它显示该错误:ValueError:x 和 y 必须具有相同的第一维,但具有形状 (512,) 和 (256,)。 我不知道如何编辑该代码。请帮忙。

import math as mt
import matplotlib.pylab as plt

N = 512
t_min = 0   # [s]
t_max = 2   # [s]
frq = 2     # [Hz]
T_p = (t_max-t_min)/N
lst = range(0, N, 1)

t = []
sinus = []
rect = []
pila1 = []
pila2 = []

for i in lst:
    t.extend([t_min + lst[i] * T_p])
    sinus.extend([mt.sin(2 * mt.pi * frq * t[i])])
    if sinus[i] > 0:
        rect.extend([True])
    else:
        rect.extend([False])
        pila1.extend([(t[i] % (1 / frq)) * frq])
        pila2.extend([abs((t[i] % (1 / frq)) * frq - 0.5) * 2])


plt.figure(1)
plt.title('Plot')
plt.plot(t, sinus)
plt.plot(t, rect)
plt.plot(t, pila1)
plt.plot(t, pila2)
plt.xlabel('t')
plt.grid(True)


plt.show()

完全错误:

    Traceback (most recent call last):
  File "venv/zadanieA.py", line 32, in <module>
    plt.plot(t, pila1)
  File "venv\lib\site-packages\matplotlib\pyplot.py", line 2761, in plot
    return gca().plot(
  File "venv\lib\site-packages\matplotlib\axes\_axes.py", line 1646, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "venv\lib\site-packages\matplotlib\axes\_base.py", line 216, in __call__
    yield from self._plot_args(this, kwargs)
  File "venv\lib\site-packages\matplotlib\axes\_base.py", line 342, in _plot_args
    raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (512,) and (256,)

【问题讨论】:

  • 欢迎来到 SO。请发布完整的错误跟踪,以便我们查看导致它的原因。如果你能解释你想要做什么,这也会很有用。
  • 在哪一行。你得到了错误。请给出完整的回溯

标签: python


【解决方案1】:

好吧,您的 t 列表包含的值与原始 lst 一样多,因为您在循环的每次迭代中添加一个项目 - 即提供 512 个项目。但是,您的pila1pila2 列表仅针对sinus[i] 的正值进行扩展,即。一半 - 所以它们只包含 256 个项目。要修复它,请将项目也添加到这些列表中(哦,请不要使用extendappend 就足够了)。

for i in lst:
    t.append(t_min + lst[i] * T_p)
    sinus.append(mt.sin(2 * mt.pi * frq * t[i]))
    if sinus[i] > 0:
        rect.append(True)
        pila1.append(0) # or whatever value you deem "neutral"
        pila2.append(0)
    else:
        rect.append(False)
        pila1.append((t[i] % (1 / frq)) * frq)
        pila2.append(abs((t[i] % (1 / frq)) * frq - 0.5) * 2)

【讨论】:

  • 谢谢,但现在我在第 19 行遇到问题 TypeError: can't multiply sequence by non-int of type 'float'
  • 检查错别字。
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2021-06-30
  • 2016-11-10
  • 1970-01-01
相关资源
最近更新 更多