Skip to content

Commit

Permalink
Specialized inv(F::SVD) (#32126)
Browse files Browse the repository at this point in the history
* inv(F::SVD)

* throw SingularException

* SingularException test

* truncate
  • Loading branch information
carstenbauer authored and andreasnoack committed Aug 13, 2019
1 parent 6527de0 commit d19bb9d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
8 changes: 8 additions & 0 deletions stdlib/LinearAlgebra/src/svd.jl
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,14 @@ function ldiv!(A::SVD{T}, B::StridedVecOrMat) where T
view(A.Vt,1:k,:)' * (view(A.S,1:k) .\ (view(A.U,:,1:k)' * B))
end

function inv(F::SVD{T}) where T
@inbounds for i in eachindex(F.S)
iszero(F.S[i]) && throw(SingularException(i))
end
k = searchsortedlast(F.S, eps(T)*F.S[1], rev=true)
@views (F.S[1:k] .\ F.Vt[1:k, :])' * F.U[:,1:k]'
end

size(A::SVD, dim::Integer) = dim == 1 ? size(A.U, dim) : size(A.Vt, dim)
size(A::SVD) = (size(A, 1), size(A, 2))

Expand Down
4 changes: 4 additions & 0 deletions stdlib/LinearAlgebra/test/svd.jl
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ using LinearAlgebra: BlasComplex, BlasFloat, BlasReal, QRPivoted
@test sf2.U*Diagonal(sf2.S)*sf2.Vt' m2

@test ldiv!([0., 0.], svd(Matrix(I, 2, 2)), [1., 1.]) [1., 1.]
@test inv(svd(Matrix(I, 2, 2))) I
@test inv(svd([1 2; 3 4])) [-2.0 1.0; 1.5 -0.5]
@test inv(svd([1 0 1; 0 1 0])) [0.5 0.0; 0.0 1.0; 0.5 0.0]
@test_throws SingularException inv(svd([0 0; 0 0]))
end

n = 10
Expand Down

0 comments on commit d19bb9d

Please sign in to comment.