Skip to content

Commit 154b382

Browse files
committed
Add Laplace expansion for det
1 parent 6f0329d commit 154b382

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/extra_functions.jl

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,31 @@ ModelingToolkit.@register Distributions.quantile(dist,x)
3838

3939
ModelingToolkit.@register Distributions.Uniform(mu,sigma)
4040
ModelingToolkit.@register Distributions.Normal(mu,sigma)
41+
42+
function LinearAlgebra.det(A::AbstractMatrix{<:Num}; laplace=true)
43+
if laplace
44+
n = LinearAlgebra.checksquare(A)
45+
if n == 2
46+
return A[1, 1] * A[2, 2] - A[1, 2] * A[2, 1]
47+
else
48+
temp = 0
49+
# Laplace expansion along the first column
50+
M′ = A[:, 2:end]
51+
for i in axes(A, 1)
52+
M = M′[(1:n) .!= i, :]
53+
d′ = A[i, 1] * det(M)
54+
if iseven(i)
55+
temp = iszero(temp) ? d′ : temp - d′
56+
else
57+
temp = iszero(temp) ? d′ : temp + d′
58+
end
59+
end
60+
end
61+
return temp
62+
else
63+
if istriu(A) || istril(A)
64+
return det(UpperTriangular(A))
65+
end
66+
return det(lu(A; check = false))
67+
end
68+
end

test/operation_overloads.jl

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ aa = a; # old a
1919

2020
# test some matrix operations don't throw errors
2121
X = [0 b c; d e f; g h i]
22-
@test iszero(simplify(det(X) - ((b * f * g) + (c * d * h) - (b * d * i) - (c * e * g)), polynorm=true))
22+
@test iszero(simplify(det(X) - ((d * ((b * i) - (c * h))) + (g * ((b * f) - (c * e))))))
2323
F = lu(X)
2424
@test F.p == [2, 1, 3]
2525
R = simplify.(F.L * F.U - X[F.p, :], polynorm=true)
@@ -85,3 +85,27 @@ M \ reshape(b,2,1)
8585
M = [1 a; 0 2]
8686
M \ b
8787
M \ [1, 2]
88+
89+
# test det
90+
@variables X[1:4,1:4]
91+
d1 = det(X, laplace=true)
92+
d2 = det(X, laplace=false)
93+
_det1 = eval(build_function(d1, X))
94+
_det2 = eval(build_function(d2, X))
95+
A = [1 1 1 1
96+
1 0 1 1
97+
1 1 0 1
98+
1 1 1 0]
99+
@test _det1(A) == -1
100+
@test _det2(A) == -1
101+
102+
@variables X[1:3,1:3]
103+
d1 = det(X, laplace=true)
104+
d2 = det(X, laplace=false)
105+
_det1 = eval(build_function(d1, X))
106+
_det2 = eval(build_function(d2, X))
107+
A = [1 1 1
108+
1 0 1
109+
1 1 1]
110+
@test _det1(A) == 0
111+
@test _det2(A) == 0

0 commit comments

Comments
 (0)