Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient & pythonic check for singular matrix

Working on some matrix algebra here. Sometimes I need to invert a matrix that may be singular or ill-conditioned. I understand it is pythonic to simply do this:

try:     i = linalg.inv(x) except LinAlgErr as err:     #handle it 

but am not sure how efficient that is. Wouldn't this be better?

if linalg.cond(x) < 1/sys.float_info.epsilon:     i = linalg.inv(x) else:     #handle it 

Does numpy.linalg simply perform up front the test I proscribed?

like image 941
Dr. Andrew Avatar asked Nov 06 '12 10:11

Dr. Andrew


People also ask

What do you mean of efficient?

Definition of efficient 1 : productive of desired effects especially : capable of producing desired results with little or no waste (as of time or materials) an efficient worker efficient machinery. 2 : being or involving the immediate agent in producing an effect the efficient action of heat in changing water to steam.

What is an example of efficient?

The definition of efficient is being productive with minimal effort. An example of efficient is a car that gets 60 miles to a gallon of gas. Making good, thorough, or careful use of resources; not consuming extra. Especially, making good use of time or energy.

Does efficient mean quick?

working or operating quickly and effectively in an organized way: The city's transportation system is one of the most efficient in Europe.


1 Answers

So based on the inputs here, I'm marking my original code block with the explicit test as the solution:

if linalg.cond(x) < 1/sys.float_info.epsilon:     i = linalg.inv(x) else:     #handle it 

Surprisingly, the numpy.linalg.inv function doesn't perform this test. I checked the code and found it goes through all it's machinations, then just calls the lapack routine - seems quite inefficient. Also, I would 2nd a point made by DaveP: that the inverse of a matrix should not be computed unless it's explicitly needed.

like image 92
Dr. Andrew Avatar answered Oct 01 '22 11:10

Dr. Andrew