0

This

a=np.zeros((20,4900))

b=np.zeros((1,4900))

a+=b

works perfectly fine. However, this:

a=np.zeros((200,49000))

b=np.zeros((10,49000))

a+=b

shows this error:

ValueError: operands could not be broadcast together with shapes (200,49000) (10,49000) (200,49000)

What might be the reason for this?

muglikar
  • 146
  • 2
  • 18

1 Answers1

3

Edit:

Numpy only lets you add two matrices of unequal dimension if and only if either matrix A or B is 1 row in height. This is called broadcasting. Basic linear algebra says that you are trying to do an invalid matrix operation since both matrices must be of the same dimensions (for addition/subtraction), so Numpy attempts to compensate for this by broadcasting.

If in your second example if your b matrix was instead defined like so:

b=np.zeros((1,49000))

There would be no error. But if you tried this:

b=np.zeros((2,49000))

It would throw the same error. Case 2 from the Numpy docs applies to your situation:

General Broadcasting Rules

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when

1.they are equal, or
2.one of them is 1

If these conditions are not met, a ValueError: frames are not aligned exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the maximum size along each dimension of the input arrays.

ifma
  • 3,673
  • 4
  • 26
  • 38
  • Sorry for the typo but I just made a correction in my question. There are indeed 49000 columns in both 'a and b' in the 2nd example. – muglikar Jul 03 '16 at 06:07
  • As Ito A writes, example 1 is adding a column to a matrix. Numpy autodetects your probable intention from the shape of a and b, it adds b to each column of a. – Freek Wiekmeijer Jul 03 '16 at 13:00
  • @Ito A So, then what is the solution? – muglikar Jul 04 '16 at 06:15
  • The solution is to obviously avoid adding two matrices of different dimensions... Set b to have either 200 rows, or just 1. – ifma Jul 04 '16 at 06:43