我正在尝试使用我的lu分解,主要基于带有部分枢轴的Matlab 的lu分解
function [L,U,P] = lup(A)
n = length(A);
L = eye(n);
U = zeros(n);
P = eye(n);
for k=1:n-1
% find the entry in the left column with the largest abs value (pivot)
[~,r] = max(abs(A(k:end,k)));
r = n-(n-k+1)+r;
A([k r],:) = A([r k],:);
P([k r],:) = P([r k],:);
L([k r],:) = L([r k],:);
% from the pivot down divide by the pivot
L(k+1:n,k) = A(k+1:n,k) / A(k,k);
U(k,1:n) = A(k,1:n);
A(k+1:n,1:n) = A(k+1:n,1:n) - L(k+1:n,k)*A(k,1:n);
end
U(:,end) = A(:,end);
end
它似乎适用于大多数矩阵(等于matlab的lu函数),但以下矩阵似乎产生了不同的结果:
A = [
3 -7 -2 2
-3 5 1 0
6 -4 0 -5
-9 5 -5 12
];
我就是搞不清楚出了什么问题。它似乎可以很好地处理链接后中提到的矩阵
您非常接近。我总共换了三行
for k=1:n-1
变成了for k=1:n
,我们不做-1,因为我们也想用你的方法得到L(n,n)=u(n,n)/u(n,n)=1
,我们忽略了
L(k+1:n,k) = A(k+1:n,k) / A(k,k);
变成L(k:n,k) = A(k:n,k) / A(k,k);
是因为您遗漏了L(k,k)=A(k,k)/A(k,k)=1
因为k+1
的变化,我们不需要从L的单位矩阵开始,因为我们现在正在对角线上复制1,所以L=eyes(n);
变成了L=zeros(n);
和完成的代码
function [L,U,P] = lup(A)
% lup factorization with partial pivoting
% [L,U,P] = lup(A) returns unit lower triangular matrix L, upper
% triangular matrix U, and permutation matrix P so that P*A = L*U.
n = length(A);
L = zeros(n);
U = zeros(n);
P = eye(n);
for k=1:n
% find the entry in the left column with the largest abs value (pivot)
[~,r] = max(abs(A(k:end,k)));
r = n-(n-k+1)+r;
A([k r],:) = A([r k],:);
P([k r],:) = P([r k],:);
L([k r],:) = L([r k],:);
% from the pivot down divide by the pivot
L(k:n,k) = A(k:n,k) / A(k,k);
U(k,1:n) = A(k,1:n);
A(k+1:n,1:n) = A(k+1:n,1:n) - L(k+1:n,k)*A(k,1:n);
end
U(:,end) = A(:,end);
end