Skip to content

Commit 490ea4e

Browse files
Optimize partial pivoting LU factorization implementation
- Simplify row swapping using slice assignment - Improve pivot selection with more concise findmax syntax - Update test case with a smaller matrix to highlight numerical stability
1 parent 64f0c5c commit 490ea4e

File tree

3 files changed

+48
-15
lines changed

3 files changed

+48
-15
lines changed

src/partial-pivoting-lu-factorization.jl

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,12 @@ function kernel(prob::PartialPivotingLUFactorizationProblem)
2727
p = collect(1:n)
2828

2929
for k in 1:n-1
30-
v, x = findmax(abs.(u[k:n, k]))
30+
v, x = findmax(i->abs(u[i, k]), k:n)
3131
x += k - 1
3232

3333
if x != k
34-
# swap row k and row x of matrix u
35-
for i in 1:n
36-
u[k, i], u[x, i] = u[x, i], u[k, i]
37-
end
38-
39-
# swap row k and row x of matrix l
40-
for i in 1:n
41-
l[k, i], l[x, i] = l[x, i], l[k, i]
42-
end
43-
44-
# swap row k and row x of matrix p
34+
u[k, :], u[x, :] = u[x, :], u[k, :]
35+
l[k, :], l[x, :] = l[x, :], l[k, :]
4536
p[k], p[x] = p[x], p[k]
4637
end
4738

src/qr-factorization.jl

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
struct QRFactorizationSolution <: SolutionMixin
2+
q::AbstractMatrix
3+
r::AbstractMatrix
4+
function QRFactorizationSolution(q, r)
5+
sol = new(q, r)
6+
@assert isortho(q) "matrix must be orthogonal"
7+
@assert istriu(r) "matrix must be upper triangular"
8+
return sol
9+
end
10+
end
11+
12+
struct QRFactorizationProblem <: ProblemMixin
13+
a::AbstractMatrix
14+
end
15+
16+
QRFactorization = QRFactorizationProblem
17+
18+
function householder_reflection!(q, r)
19+
m, n = size(r)
20+
21+
if m == 1
22+
return q, r
23+
else
24+
h = Matrix{Float64}(I, m, m)
25+
for i in 1:m-1
26+
h[i+1:m, i] = -2 * r[i+1:m, i] / r[i, i]
27+
end
28+
q = h * q
29+
r = h * r
30+
householder_reflection!(q, r)
31+
end
32+
end
33+
34+
function kernel(prob::QRFactorizationProblem)
35+
r = copy(prob.a)
36+
n = size(r, 1)
37+
q = Matrix{Float64}(I, n, n)
38+
39+
40+
end
41+
42+
export PartialPivotingLUFactorization

test/partial-pivoting-lu-factorization.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
@testset "Partial pivoting LU factorization" begin
2-
n = 4
3-
tol = 1e-10
4-
a = rand(n, n)
2+
tol = 1e-6
3+
a = [1e-8 1; 1 1]
4+
n = size(a, 1)
55

66
p = PartialPivotingLUFactorization(a, tol)
77
s = kernel(p)

0 commit comments

Comments
 (0)