I have a function called mult2
that takes in two square NumPy matrices and returns a matrix that is the result of a special multiplication:
p=P(1,344)
PI,PIT=[],[]
for i in xrange(344):
PI.append(p**i)
PIT.append((p**i).transpose())
def mult2(a,b):
C=np.sum((a*b)**2,axis=1)
CE1=np.matrix([[0.0] for _ in xrange(len(a))])
API,PITB=[],[]
AB=a*b
for i in xrange(len(a)):
API.append(np.diag(np.diag(a*PI[i])))
PITB.append(np.diag(np.diag(PIT[i]*b)))
CE1+=np.sum(API[i]*PITB[i]*AB,axis=1)
CE2=np.matrix([[0.0] for _ in xrange(len(a))])
BPI,PITA=[],[]
for i in xrange(len(a)):
BPI.append(np.diag(np.diag(b*PI[i])))
PITA.append(np.diag(np.diag(PIT[i]*a)))
CE2+=np.sum(a*BPI[i]*PITA[i]*b,axis=1)
CE3=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
CE3+=np.sum(AB*API[i]*PITB[i],axis=1)
CE1E2=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
CE1E2+=np.sum(API[i]*PITB[i]*API[i]*PIT[i]*b,axis=1)
CE2E3=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
CE2E3+=np.sum(a*BPI[i]*PITA[i]*BPI[i]*PIT[i],axis=1)
CE1E3=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
for j in xrange(len(a)):
CE1E3+=np.sum(np.matrix(API[i]*PITB[i]*API[j]*PITB[j]),axis=1)
CE1E2E3=np.matrix([[0.0] for _ in xrange(len(a))])
for i in xrange(len(a)):
CE1E2E3+=np.sum(np.matrix((API[i]*PITB[i])**2),axis=1)
return C-(CE1+CE2+CE3-CE1E2-CE1E3-CE2E3+CE1E2E3)
p
is another matrix of the same dimensions (n
by n
) as a
and b
specially a circulant matrix.
My trouble is that these matrices are 344 by 344 and I am looking to run this function lots of times.
Storing the matrices that are used later in the function in the lists actually sped up the computation significantly.
I know this is a very intensive computation so it should take a while to run. That being said, can anyone spot any improvements I can make?