lorenzo
lorenzo

Reputation: 35

ValueError: could not broadcast input array from shape (25,1) into shape (25)

when I am trying to run this simple snippet of code

a= 2

G = np.random.rand(25,1)
H = np.zeros((25,a))

for i in range(a):
    H[:,i] = .5 * G 

I receive the

ValueError: could not broadcast input array from shape (25,1) into shape (25). 

I wonder if anyone can point at a solution to this problem?

I know it happens quite a bit in image processing, but this one, I don't knwo how to circumvent.

Cheers.

Upvotes: 2

Views: 9234

Answers (1)

Alex
Alex

Reputation: 19104

To fix this you use the first column of G:

for i in range(a):
    H[:,i] = .5 * G[:, 0]

Numpy broadcasting basically attempts to match dimensions of arrays (when broadcasting) by starting with the last dimension and moving to the first. In this case the second dimension of G (1) gets broadcast to 25 (the first and only dimension of H[:, i]. The first dimension of G does not match with anything. You can read more about numpy broadcasting rules here.

Note: you really don't need that for loop. H is just G column repeated twice. You can accomplish that in various ways (e.g. np.tile, np.hstack, etc.)

H = np.tile(G / 2, 2)

Upvotes: 4

Related Questions