user2352414
user2352414

Reputation: 21

ValueError with Python and Numpy

I'm trying to rebuild a song in python, but I cannot concatenate the notes of the same. I get this error:

ValueError: operands could not be broadcast together with shapes (0) (1250)

Here's my code:

import numpy as np, matplotlib.pyplot as plt

def nota(f,d):
    ts = 0.0002
    t  = np.arange(0, d, ts)
    X  = 5500*np.cos(2*np.pi*f*t)
    return X

# II.2.b)
pausa    = nota(0,0)
La       = nota(440,0.25)
Mi       = nota(659.26,0.25)
Do       = nota(253.25,0.25)
Sol      = nota(783.99,0.25)
Si       = nota(493.88,0.25)
Solbemol = nota(830.61,0.25)

def FurElise():
    musica = np.array((pausa,pausa,La,Mi,La,pausa,pausa,Mi,Mi,Solbemol,    \
                       pausa,pausa,La,Mi,La,pausa,pausa,pausa,La,Mi,La,    \
                       pausa,pausa,Mi,Mi,Solbemol,pausa,pausa,La,Mi,La,    \
                       pausa,Do,Sol,Do,pausa,pausa,Sol,Sol,Si,pausa,pausa, \
                       La,Mi,La,pausa,pausa,Mi,Mi,Mi,pausa))
    y=0
    for x in musica:
        z=np.hstack((x,y))
        y = y+x
    z=np.hstack((x,y))
    plt.plot(z)
    plt.show()

FurElise()

Upvotes: 2

Views: 443

Answers (2)

askewchan
askewchan

Reputation: 46530

You create musica (assuming that you've fixed pausa as described by @fgb) by stacking the 51 notes as rows in a 2D array. So, musica.shape is (51, 1250)

I think that you want z to be a long 1D array where all the notes are in one row, instead of each in their own row. There are two solutions. One, is to say:

musica = np.array((pausa,pausa,La,Mi,La,...))
z = musica.flatten()
plt.plot(z)

and completely remove all of this:

y=0
for x in musica:
    z=np.hstack((x,y))
    y = y+x
z=np.hstack((x,y))

A better solution is to make musica a 1D array when you create it:

musica = np.hstack((pausa,pausa,La,Mi,La,...))
plt.plot(musica)

This takes all the notes (pausa, La, etc) and stacks them horizontally (so that they're all in one row together), so you never need to flatten or concatenate anything.

Upvotes: 1

fgb
fgb

Reputation: 3119

As @filmor notes, x and y are of different shapes, and the reason for that is your definition of pausa = nota(0,0). By using a d value of 0, the resulting array is of length 0 while all other arrays are of length 1250, and y = y+x will eventually throw the error you're seeing (e.g. after 3 iterations, given your current definition of musica).

Assuming you want the pause to be of the same length as all other notes, you can re-define pausa so as to get rid of the error:

pausa = nota(0,0.25)

Upvotes: 3

Related Questions