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?

Asked By: Mino

||

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]
Answered By: I'mahdi

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)

Answered By: manavmalaviya
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.