Home > Enterprise >  Is there a faster way of creating 3x3 matrices from multiple matrices for eigenvalue and eigenvector
Is there a faster way of creating 3x3 matrices from multiple matrices for eigenvalue and eigenvector

Time:03-29

I am trying to calculate eigenvalues and eigenvectors for multiple 3x3 matrices. I have 6 (e11, e12, e13, e22, e23, e33) mxn shaped matrices and each 3x3 matrix is formed using each element from these 6 matrices. The number of elements in these 6 matrices is in the thousands. Right now I just loop through these matrices and create a 3x3 matrix at each pass and calculate eigenvalue and eigenvectors and it takes almost 10 mins to compute. I know there must be a better way. I am not an expert in python so any help to speed up my code would be appreciated.

See my code below:

for i in range(0,m):
    for j in range(0,n):
        E = np.array([ [e11[i][j], e12[i][j], e13[i][j]],
                       [e12[i][j], e22[i][j], e23[i][j]],
                       [e13[i][j], e23[i][j], e33[i][j]] ])

        e_val, e_vec = np.linalg.eig(E)

CodePudding user response:

If I create a set of (3,4) arrays, I can combine them with

In [149]: e11,e12,e22 = [np.ones((3,4))*i for i in range(1,4)]
In [150]: E1=np.stack((np.stack([e11,e12],-1), np.stack([e12,e22],-1)),-1)
In [151]: E1.shape
Out[151]: (3, 4, 2, 2)

That can be passed to eig to produce:

In [153]: np.linalg.eig(E)[0].shape
Out[153]: (3, 4, 2)

I'll let you generalize to your (3,3) case

CodePudding user response:

As per the suggestion from @hpaulj, I modified my code as below which reduced my computation time from 10 min to 40 seconds.

E = np.stack([np.stack([e11,e12,e13],-1),np.stack([e12,e22,e23],-1),np.stack([e13,e23,e33],-1)],-1)

e_val, e_vec = np.linalg.eig(E)

so now the e_val and e_vec have all the eigenvalues and eigenvectors respectively.

  • Related