How to solve: ValueError: operands could not be broadcast together with shapes (4,) (4,6)

Question:

I have to sum 2 arrays with broadcasting. This is the first:

a = [0 1 2 3]

And this is the second:

A = [[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]

This is the code I had tried until now:

a = np.array(a)
A = np.array(A)
G = a + A
print(G)

But when I run, it throws this error: ValueError: operands could not be broadcast together with shapes (4,) (4,6)

How to solve it?

Asked By: user12268725

||

Answers:

Arrays need to have compatible shapes and same number of dimensions when performing a mathematical operation. That is, you can’t add two arrays of shape (4,) and (4, 6), but you can add arrays of shape (4, 1) and (4, 6).

You can add that extra dimension as follows:

a = np.array(a)
a = np.expand_dims(a, axis=-1) # Add an extra dimension in the last axis.
A = np.array(A)
G = a + A

Upon doing this and broadcasting, a will practically become

[[0 0 0 0 0 0]
 [1 1 1 1 1 1]
 [2 2 2 2 2 2]
 [3 3 3 3 3 3]]

for the purpose of addition (the actual value of a won’t change, a will still be [[0] [1] [2] [3]]; the above is the array A will be added to).

Answered By: Susmit Agrawal