python - Efficient way to fill up a 4d array from entries of a product of two matrices -
title might not precise hoped, here problem. i'm filling 4d numpy array entries of product of 2 matrices. right code following :
m = p.dot(u) c_arr = np.zeros((b_size,b_size,n,n)) alpha in xrange(b_size): beta in xrange(b_size): in xrange(n): j in xrange(n): c_arr[alpha,beta,i,j] = np.conjugate(m[i,alpha])*m[j,beta] it turns out function called quite ofen , appears time-consumming. i'm beginning python , suspect there more efficient way write function avoiding loops, haven't been able figure out myself...
you can use numpy.einsum:
c = np.einsum('ia,jb->abij', m.conj(), m) or, since there no actual sum being computed (i.e. form of outer product), can use numpy broadcasting regular array multiplication after reshaping input matrix m appropriately:
nrows, ncols = m.shape c = m.t.reshape(1, ncols, 1, nrows) * m.t.conj().reshape(ncols, 1, nrows, 1)
Comments
Post a Comment