简体   繁体   中英

ValueError: x and y must have same first dimension, but have shapes (512,) and (256,)

I tried to use numpy and np.array but it fails. It displays that error: ValueError: x and y must have same first dimension, but have shapes (512,) and (256,). I dont know how to edit that code. Please help.

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

there is full error:

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

Well, your t list contains as many values as the original lst , as you add one item in every iteration of the loop - that gives 512 items. However, your pila1 and pila2 lists are extended only for positive values of sinus[i] , ie. half as many - so they contain only 256 items. To fix it, add items to these list as well (oh, and please do not use extend where append suffices).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM