I'd like to sum every n columns of a matrix. How can I do that in a simple way without using a for loop? This is what I have now:
n = 3 #size of a block we need to sum over
total = 4 #total required sums
ncols = n*total
nrows = 10
x = np.array([np.arange(ncols)]*nrows)
result = np.empty((total,nrows))
for i in range(total):
result[:,i] = np.sum(x[:,n*i:n*(i+1)],axis=1)
The result will be
array([[ 3., 12., 21., 30.],
[ 3., 12., 21., 30.],
...
[ 3., 12., 21., 30.]])
How can I vectorize this operation?