A really stupid question, but I could not figure the right way..
- A is a 2 by 2 matrix, and B is a 2 by 1 matrix.
- In a 10 iterations loop, B_new=A*B. B_new is 2 by 1.
- Save B_new to an output matrix B_final after each iteration. So in the end, B_final is 2 by 10.
However, I have problem of adding B to B_new in a loop. Below is my code, can anyone give me some suggestions?
import numpy as np
a=np.ones(shape=(2,2))
b=np.ones(shape=(2,1))
c_final=np.zeros(shape=(2,10))
for i in range(0,10):
c=np.dot(a,b)
b=c
c_final[:,i]=c
Here is the error message:
c_final[:,i]=c
ValueError: output operand requires a reduction, but reduction is not enabled
The error you’re seeing is because when numpy broadcasts
c_final[:,i]andnp.dot(a,b)together it produces an array with shape(2,2), which then can’t be assigned toc_final[:,i]since it has a shape of(2,1). I think it’s much clearer if you just play around with it in the interpreter:The way around this is to flatten
np.dot(a,b)by usingnp.squeezeor something similar so that when they are broadcast together they produce a 2 element array. For example:You’re not alone in finding the error message unhelpful. Someone filed a ticket about this about a year ago.