Reputation: 164
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?
Upvotes: 0
Views: 7293
Reputation: 3818
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.
Upvotes: 3