Skip to content

Commit d19bb9d

Browse files
carstenbauerandreasnoack
authored andcommitted
Specialized inv(F::SVD) (#32126)
* inv(F::SVD) * throw SingularException * SingularException test * truncate
1 parent 6527de0 commit d19bb9d

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

stdlib/LinearAlgebra/src/svd.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,14 @@ function ldiv!(A::SVD{T}, B::StridedVecOrMat) where T
238238
view(A.Vt,1:k,:)' * (view(A.S,1:k) .\ (view(A.U,:,1:k)' * B))
239239
end
240240

241+
function inv(F::SVD{T}) where T
242+
@inbounds for i in eachindex(F.S)
243+
iszero(F.S[i]) && throw(SingularException(i))
244+
end
245+
k = searchsortedlast(F.S, eps(T)*F.S[1], rev=true)
246+
@views (F.S[1:k] .\ F.Vt[1:k, :])' * F.U[:,1:k]'
247+
end
248+
241249
size(A::SVD, dim::Integer) = dim == 1 ? size(A.U, dim) : size(A.Vt, dim)
242250
size(A::SVD) = (size(A, 1), size(A, 2))
243251

stdlib/LinearAlgebra/test/svd.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ using LinearAlgebra: BlasComplex, BlasFloat, BlasReal, QRPivoted
3131
@test sf2.U*Diagonal(sf2.S)*sf2.Vt' m2
3232

3333
@test ldiv!([0., 0.], svd(Matrix(I, 2, 2)), [1., 1.]) [1., 1.]
34+
@test inv(svd(Matrix(I, 2, 2))) I
35+
@test inv(svd([1 2; 3 4])) [-2.0 1.0; 1.5 -0.5]
36+
@test inv(svd([1 0 1; 0 1 0])) [0.5 0.0; 0.0 1.0; 0.5 0.0]
37+
@test_throws SingularException inv(svd([0 0; 0 0]))
3438
end
3539

3640
n = 10

0 commit comments

Comments
 (0)