Mechanician
Mechanician

Reputation: 545

Vectorizing eigen value calculation in numpy python

I am trying to arrange each row of A into a matrix and then compute the eigenvalues. I need to help to vectorize this operation.

A= np.array([[5, 5, 7, 0, 1, 6], 
          [4, 0, 9, 3, 4, 0],
          [3, 1, 2, 0, 1, 1],
          [7, 6, 4, 4, 1, 8], 
          [3, 1, 9, 8, 0, 1], 
          [8, 6, 1, 4, 3, 6], 
          [6, 9, 5, 9, 6, 1], 
          [5, 9, 6, 8, 3, 3]])

S1 = A[:,0]
S2 = A[:,1]
S3 = A[:,2]
S4 = A[:,3]
S5 = A[:,4]
S6 = A[:,5]

SS=[(S1,S4,S5),(S4,S2,S6),(S5,S6,S3)]
SS=np.array(SS)
reqval=np.zeros([len(A),1])

for i in range(len(A)):
    eva = np.linalg.eigvals(SS[:,:,i])
    reqval[i] = max(eva)

Upvotes: 1

Views: 93

Answers (1)

Divakar
Divakar

Reputation: 221524

Permute axes with transpose/rollaxis/moveaxis, such that we bring the first two axes as the last two ones and that lets us use np.linalg.eigvals with a single call, like so -

reqval = np.linalg.eigvals(SS.transpose(2,0,1)).max(1)

To use rollaxis and moveaxis, use : np.rollaxis(SS,2,0) and np.moveaxis(SS,2,0) respectively in place of SS.transpose(2,0,1).

Upvotes: 1

Related Questions