Computes the LU factorization Input arguments: A, square matrix Output arguments: L, square matrix of the same dimensions as A containing the lower triangular portion of the LU factorization U, square matrix of the same dimensions as A containing the upper triangular portion of the LU factorization
0001 function [L,U]=LU(A) 0002 % Computes the LU factorization 0003 % Input arguments: 0004 % A, square matrix 0005 % Output arguments: 0006 % L, square matrix of the same dimensions as A containing the lower 0007 % triangular portion of the LU factorization 0008 % U, square matrix of the same dimensions as A containing the upper 0009 % triangular portion of the LU factorization 0010 0011 [n,m]=size(A); % finding the size of A 0012 if n~= m 0013 error('input is not a square matrix'); 0014 end 0015 L=eye(n); % initializing L to the identity matrix 0016 U=A; % initializing U to be A 0017 for k=1:n % loop calculates one column of L and one row of U at a time 0018 % Note that U holds in its lower portion a modified portion of A 0019 for j=k+1:n 0020 % if U(k,k) = 0, do nothing, because L is already initialized 0021 % to the identity matrix and thus the k-th column is the k-th 0022 % standard basis vector 0023 if abs(U(k,k)) > 1e-12 % not comparing to zero because of 0024 % possible rounding errors 0025 L(j,k)=U(j,k)/U(k,k); % let the k-th column of L be the k-th 0026 % column of the current U scaled by 0027 % the diagonal element 0028 end 0029 U(j,:)=U(j,:)-L(j,k)*U(k,:); % adjust U by subtracting the 0030 % outer product of of the k-th 0031 % column of L and the k-th row 0032 % of U 0033 end 0034 end