Blo*_*911 3 matlab matrix-decomposition
我正在尝试使用我的 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
Run Code Online (Sandbox Code Playgroud)
它似乎适用于大多数矩阵(等于 matlab lu 函数),但是以下矩阵似乎会产生不同的结果:
A = [
3 -7 -2 2
-3 5 1 0
6 -4 0 -5
-9 5 -5 12
];
Run Code Online (Sandbox Code Playgroud)
我只是不明白出了什么问题。它似乎在链接帖子中提到的矩阵上运行良好
你已经很接近了。我总共改变了三行
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
Run Code Online (Sandbox Code Playgroud)