MATLAB LU Decomposition Partial pivoting

大憨熊 提交于 2019-12-06 11:02:50

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