1

I am developing custom regression analysis routine and ran into a problem trying to call tuple element for calculations:

EV = np.linalg.eig(xMe)
print EV

The result of print EV is below:

(array([  4.59554481e-02,   1.73592040e+04]), matrix([[-0.99977087, -0.02140571],
    [ 0.02140571, -0.99977087]])) 

It is a tuple. I need to access each element in the first array in tuple ( 4.59554481e-02, 1.73592040e+04). When I try to convert tuple using:

lEV = np.asarray(EV)

I get the following error:

ValueError                                Traceback (most recent call last)
<ipython-input-172-f46907801d9e> in <module>()
 42 print EV
 43 
---> 44 lEV = np.asarray(EV)

462     return array(a, dtype, copy=False, order=order)
463 
464 def asanyarray(a, dtype=None, order=None):

ValueError: could not broadcast input array from shape (2,2) into shape (2)

I am new to Python and probably there is a very easy way to access these two elements but I can not figure it out.

1
  • 1
    Silly of me:) It is easy: m= EV[0] and then call m[0] and m[1]. Any optimization suggestions are greatly appreciated Commented Sep 18, 2015 at 3:32

1 Answer 1

1

A pythonic way to do this would be to use tuple unpacking:

>>> import numpy as np

>>> a = np.array([[0,17],[42,23]])
>>> eigenvalues, eigenvectors = np.linalg.eig(a)
>>> print eigenvalues
array([-17.59037642,  40.59037642])

>>> print eigenvectors
array([[-0.69493692, -0.38630591],
       [ 0.71907071, -0.92237072]])

This allows you to unpack the two items of the tuple into two variables. On those variables you can now use a standard for loop:

>>> for value in eigenvalues:
...    print(value)
-17.5903764156
40.5903764156

Alternatively (if you know how many values you will get) you can use tuple unpacking again:

>>> ev_1, ev_2 = eigenvalues
>>> print ev_1
-17.5903764156

>>> print ev_2
40.5903764156
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.