|
| 1 | +using StaticArrays, Test, LinearAlgebra |
| 2 | + |
| 3 | +tol = 1e-13 |
| 4 | + |
| 5 | +@testset "Moore–Penrose inverse (Peseudo-inverse)" begin |
| 6 | + M1 = @SMatrix [1.5 1.3; 1.2 1.9] |
| 7 | + N1 = pinv(M1) |
| 8 | + @test norm(M1*N1*M1 - M1) < tol |
| 9 | + @test norm(N1*M1*N1 - N1) < tol |
| 10 | + @test N1 isa SMatrix{2,2,Float64} |
| 11 | + @test N1 ≈ pinv(Matrix(M1)) |
| 12 | + |
| 13 | + M2 = @SMatrix [1//2 0 0;3//2 5//3 8//7;9//4 -1//3 -8//7;0 0 0] |
| 14 | + N2 = pinv(M2) |
| 15 | + @test norm(M2*N2*M2 - M2) < tol |
| 16 | + @test norm(N2*M2*N2 - N2) < tol |
| 17 | + @test N2 isa SMatrix{3,4,Float64} |
| 18 | + @test N2 ≈ pinv(Matrix(M2)) |
| 19 | + |
| 20 | + M3 = SDiagonal(0,1,2,3) |
| 21 | + N3 = pinv(M3) |
| 22 | + @test norm(M3*N3*M3 - M3) < tol |
| 23 | + @test norm(N3*M3*N3 - N3) < tol |
| 24 | + @test N3 isa Diagonal{Float64, <:SVector{4,Float64}} |
| 25 | + @test N3 ≈ pinv(Matrix(M3)) |
| 26 | + |
| 27 | + M4 = @SMatrix randn(2,5) |
| 28 | + N4 = pinv(M4) |
| 29 | + @test norm(M4*N4*M4 - M4) < tol |
| 30 | + @test norm(N4*M4*N4 - N4) < tol |
| 31 | + @test N4 isa SMatrix{5,2,Float64} |
| 32 | + @test N4 ≈ pinv(Matrix(M4)) |
| 33 | + |
| 34 | + M5 = SMatrix{0,5,Int}() |
| 35 | + N5 = pinv(M5) |
| 36 | + @test norm(M5*N5*M5 - M5) < tol |
| 37 | + @test norm(N5*(M5*N5) - N5) < tol |
| 38 | + @test N5 isa SMatrix{5,0,Float64} |
| 39 | + @test N5 ≈ pinv(Matrix(M5)) |
| 40 | + |
| 41 | + M6 = @SMatrix [1/2 0 0;0 5/3 0;0 0 0;0 0 0] |
| 42 | + N6 = pinv(M6) |
| 43 | + @test norm(M6*N6*M6 - M6) < tol |
| 44 | + @test norm(N6*M6*N6 - N6) < tol |
| 45 | + @test N6 isa SMatrix{3,4,Float64} |
| 46 | + @test N6 ≈ I(3)/Matrix(M6) |
| 47 | + # @test N6 ≈ pinv(Matrix(M6)) # Fails on Julia ≥v1.7 https://github.com/JuliaLang/julia/issues/44234 |
| 48 | + |
| 49 | + M7 = M6' |
| 50 | + N7 = pinv(M7) |
| 51 | + @test norm(M7*N7*M7 - M7) < tol |
| 52 | + @test norm(N7*M7*N7 - N7) < tol |
| 53 | + @test N7 isa SMatrix{4,3,Float64} |
| 54 | + @test N7 ≈ I(4)/Matrix(M7) |
| 55 | + # @test N7 ≈ pinv(Matrix(M7)) # Fails on Julia ≥v1.7 https://github.com/JuliaLang/julia/issues/44234 |
| 56 | + |
| 57 | + M8 = @MMatrix [0.5 1.1 0.0;0.0 -2.8 0.0;0.0 0.0 0.0;0.0 0.0 0.0] |
| 58 | + N8 = pinv(M8) |
| 59 | + @test norm(M8*N8*M8 - M8) < tol |
| 60 | + @test norm(N8*M8*N8 - N8) < tol |
| 61 | + @test N8 isa MMatrix{3,4,Float64} |
| 62 | + @test N8 ≈ pinv(Matrix(M8)) |
| 63 | + |
| 64 | + M9 = M8' |
| 65 | + N9 = pinv(M9) |
| 66 | + @test norm(M9*N9*M9 - M9) < tol |
| 67 | + @test norm(N9*M9*N9 - N9) < tol |
| 68 | + @test N9 isa MMatrix{4,3,Float64} |
| 69 | + @test N9 ≈ pinv(Matrix(M9)) |
| 70 | + |
| 71 | + M10 = @SMatrix randn(3,3) |
| 72 | + N10 = pinv(M10) |
| 73 | + @test N10 ≈ inv(M10) |
| 74 | + @test norm(M10*N10*M10 - M10) < tol |
| 75 | + @test norm(N10*M10*N10 - N10) < tol |
| 76 | + @test N10 isa StaticMatrix |
| 77 | + @test N10 ≈ pinv(Matrix(M10)) |
| 78 | +end |
0 commit comments