我无法找到我尝试使用here (page 6)的伪代码部分旋转实现LU分解的错误。我的代码粘贴在下面。有谁能发现问题?
def LUPdecomposition(matrix):
n, m = matrix.shape
assert n == m, "LU decomposition is only applicable to square matrices"
L = np.identity(n)
U = matrix.copy()
P = np.identity(n)
for k in range(n-1):
# pivoting: get index of maximum in k-th column on diagonal or below
index = np.argmax(abs(U[k:,k]))
index += k
# pivoting: permute rows
if index != k:
U[[index,k],k:n] = U[[k,index],k:n]
P[[index,k]] = P[[k,index]]
if index > 0:
L[[index,k],0:(k-1)] = L[[k,index],0:(k-1)]
# calculating next column in L and modifing rows in U
for j in range(k+1,n):
L[j,k] = U[j,k] / U[k,k]
U[j,k:] -= L[j,k]*U[k,k:]
return L,U,P
答案 0 :(得分:0)
下面的代码可以解决该问题。比较scipy结果和您提供的链接是可以的。但是,scipy库会转置P矩阵。
import numpy as np
def LU_partial_decomposition(matrix):
n, m = matrix.shape
P = np.identity(n)
L = np.identity(n)
U = matrix.copy()
PF = np.identity(n)
LF = np.zeros((n,n))
for k in range(0, n - 1):
index = np.argmax(abs(U[k:,k]))
index = index + k
if index != k:
P = np.identity(n)
P[[index,k],k:n] = P[[k,index],k:n]
U[[index,k],k:n] = U[[k,index],k:n]
PF = np.dot(P,PF)
LF = np.dot(P,LF)
L = np.identity(n)
for j in range(k+1,n):
L[j,k] = -(U[j,k] / U[k,k])
LF[j,k] = (U[j,k] / U[k,k])
U = np.dot(L,U)
np.fill_diagonal(LF, 1)
return PF, LF, U
# Usage
A = [[2, 1, 1, 0], [4, 3, 3, 1], [8, 7, 9, 5], [6, 7, 9, 8]]
A = np.array(A)
P1, L1, U1 = LU_partial_decomposition(A)
# Scipy
import scipy
import scipy.linalg
P2, L2, U2 = scipy.linalg.lu(A) # P2 = P2.T