MATLAB LU分解部分旋转

时间:2015-03-30 23:35:58

标签: matlab matrix-decomposition

我尝试使用我的lu分解主要基于LU decomposition with partial pivoting Matlab

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
];

我无法弄清楚出了什么问题。它似乎在链接帖子中提到的矩阵上运行良好

1 个答案:

答案 0 :(得分:3)

你非常接近。我改变了总共三行

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