MATLAB LU Decomposition Partial pivoting

你。 提交于 2019-12-07 18:53:33

问题


I'm trying to work with my lu decomposition largely based on 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

It seems to work for most matrices (equal to the matlab lu function), however the following matrix seems to produce different results:

A = [
 3    -7    -2     2
-3     5     1     0
 6    -4     0    -5
-9     5    -5    12
];

I just can't figure out what is going wrong. It seems to work fine on the matrices mentioned in the linked post


回答1:


you were pretty close. I changed three lines total

for k=1:n-1 became for k=1:n we don't do the -1 because we also want to get L(n,n)=u(n,n)/u(n,n)=1 with your method we were leaving this out

L(k+1:n,k) = A(k+1:n,k) / A(k,k); became L(k:n,k) = A(k:n,k) / A(k,k); because you were leaving out L(k,k)=A(k,k)/A(k,k)=1

because the k+1 change we dont need to start with an identity matrix for L since we are now reproducing the 1's on the diagonals so L=eyes(n); became L=zeros(n);

and the completed code

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


来源:https://stackoverflow.com/questions/29358167/matlab-lu-decomposition-partial-pivoting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!