Python: Why can't I add a 3×1 array to one column of a 3×100 array?
Question:
Variable a
has the shape (3,1) and variable b
has the shape (3,100). Now, I want to add variable a
to just one column of variable b
, meaning:
x[:,ii] = a + b[:,ii]
However, I get this message:
could not broadcast input array from shape (3,3) into shape (3,)
What am I missing?
Answers:
You need to use numpy.ravel()
Because a.shape
is (3,1)
and you need (3,)
.
x[:,ii] = a.ravel() + b[:,ii]
# Or By thanks `@Raphael` we can use `np.squeeze()`
# x[:,ii] = a.squeeze() + b[:,ii]
because the shape is 3 X 1 and 3×100, to multiply the column of first matrix and row of second matrix should be same(for eg. it would work it the matrix’s are 3×1 X 1×100)
Variable a
has the shape (3,1) and variable b
has the shape (3,100). Now, I want to add variable a
to just one column of variable b
, meaning:
x[:,ii] = a + b[:,ii]
However, I get this message:
could not broadcast input array from shape (3,3) into shape (3,)
What am I missing?
You need to use numpy.ravel()
Because a.shape
is (3,1)
and you need (3,)
.
x[:,ii] = a.ravel() + b[:,ii]
# Or By thanks `@Raphael` we can use `np.squeeze()`
# x[:,ii] = a.squeeze() + b[:,ii]
because the shape is 3 X 1 and 3×100, to multiply the column of first matrix and row of second matrix should be same(for eg. it would work it the matrix’s are 3×1 X 1×100)