Skip to content

Commit

Permalink
Use SVD for computing the condition number of matrices (#1862)
Browse files Browse the repository at this point in the history
Return Inf for singular matrices.
cond(A,2) also returns NaN for all zeros input.

To fix:
cond(A,p) returns Inf for all zeros input except when p = 2.
  • Loading branch information
ViralBShah committed Jan 1, 2013
1 parent 68e09fb commit ac0c1cd
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions base/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,19 @@ trace(A::AbstractMatrix) = sum(diag(A))

#det(a::AbstractMatrix)
inv(a::AbstractMatrix) = a \ one(a)
cond(a::AbstractMatrix, p) = norm(a, p) * norm(inv(a), p)
cond(a::AbstractMatrix) = cond(a, 2)
cond(a::AbstractMatrix) = (s = svdvals(a); max(s) / min(s))

function cond(a::AbstractMatrix, p)
if p == 2
return cond(a)
else
try
return norm(a, p) * norm(inv(a), p)
catch SingularException

This comment has been minimized.

Copy link
@JeffBezanson

JeffBezanson Jan 1, 2013

Member

This catches all exceptions, which I realize might be deliberate since there is no SingularException type. Maybe it should only trap LapackException? Also, is there a way to check that a system is singular without catching exceptions?

This comment has been minimized.

Copy link
@ViralBShah

ViralBShah Jan 1, 2013

Author Member

I would use the LU Decomposition from LAPACK and check the return code in there for singular systems.

return Inf
end
end
end

#issym(A::AbstractMatrix)
#ishermitian(A::AbstractMatrix)
Expand Down

2 comments on commit ac0c1cd

@JeffBezanson
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is p=2 a special case that should give NaN? Not my area of expertise, but sounds fishy to me.

@ViralBShah
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

p=2 should not give NaN when the input is all zeros. It just comes out of the computation (due to 0/0) right now. I wanted to avoid checking the input being a matrix of all zeros, but that is the only way out.

I have noted it in the issue, that it has yet to be fixed:
#1862

Please sign in to comment.