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