Innumerical analysis andlinear algebra,lower–upper (LU)decomposition orfactorization factors amatrix as the product of a lowertriangular matrix and an upper triangular matrix (seematrix multiplication andmatrix decomposition). The product sometimes includes apermutation matrix as well. LU decomposition can be viewed as the matrix form ofGaussian elimination. Computers usually solve squaresystems of linear equations using LU decomposition, and it is also a key step when inverting a matrix or computing thedeterminant of a matrix. It is also sometimes referred to asLR decomposition (factors into left and right triangular matrices). The LU decomposition was introduced by the Polish astronomerTadeusz Banachiewicz in 1938,[1] who first wrote product equation (The last form in his alternate yet equivalent matrix notation appears as). While most ellimination and LU algorithms employ equations of the form Banachiewicz wrote it as, in this way revealing additional problem symmetry.

LetA be a square matrix. AnLU factorization refers to expression ofA into product of two factors – a lower triangular matrixL and an upper triangular matrixU:A =LU. Sometimes factorization is impossible without prior reordering ofA to prevent division by zero or uncontrolled growth of rounding errors hence alternative expression becomesPAQ =LU, where in formal notationpermutation matrices factorsP andQ indicate permutation of rows (or columns) ofA. In theoryP (orQ) are obtained by permutations of rows (or columns) of theidentity matrix, in practice the corresponding permutations are applied directly to rows (or columns) ofA.
MatrixA of siden has coefficients while two triangle matrices combined containn(n + 1) coefficients, thereforen coefficients of matricesLU are not independent. Usual convention is to setL unitriangular, i.e. with alln main diagonal elements equal one. However, setting insteadU matrix unitriangular reduces to the same procedure aftertranspose of matrix product (cf. properties of matrix transposition):After transposition,UT is lower triangle whileLT is upper unitriangular factor ofB. This demonstrates also, that operations on rows (e.g. pivoting) are equivalent to those on columns of a transposed matrix, and in general choice of row or column algorithm offers no advantage.
In the lower triangular matrix all elements above the main diagonal are zero, in the upper triangular matrix, all the elements below the diagonal are zero. For example, for a3 × 3 matrixA, its LU decomposition looks like this:
Without a proper ordering or permutations in the matrix, the factorization may fail to materialize. For example, it is easy to verify (by expanding thematrix multiplication) that. If, then at least one of and has to be zero, which implies that eitherL orU issingular. This is impossible ifA is nonsingular (invertible). In terms of operations, zeroing/elimination of remaining elements of first column ofA involves division of with, impossible if it is 0. This is a procedural problem. It can be removed by simply reordering the rows ofA so that the first element of the permuted matrix is nonzero. The same problem in subsequent factorization steps can be removed the same way. For numerical stability against rounding errors/division by small numbers it is important to select of large absolute value (cf. pivoting).
The above example of3 × 3 matrices demonstrates that matrix product of top row and leftmost columns of involved matrices plays special role forLU to succeed. Let us mark consecutive versions of matrices with and then let us write matrix product in such way that these rows and columns are separated from the rest. In doing so we shall useblock matrix notation, such that e.g. is an ordinary number, is a row vector and is a column vector and is sub-matrix of matrix without top row and leftmost column. Then we can replace with a blockmatrix product. Namely it turns out that one can multiply matrix blocks in such way as if they were ordinary numbers, i.e. row times column, except that now their components are sub-matrices, sometimes reduced to scalars or vectors. Thus denotes a vector obtained from after multiplication of each component by a number, is anouter product of vectors, i.e. a matrix which first column is, next is and so on for all components of and is a product of sub-matrices of
From equality of first and last matrices follow final,, while matrix becomes updated/replaced with. Now comes the crucial observation: nothing prevents us to treat the same way as we did with, repeatedly. If dimension of isn × n, aftern− 1 such steps all columns form sub-diagonal part of triangle matrix and all pivots combined with rows form upper triangle matrix, as required. In the above examplen = 3 so only two steps suffice.
The above procedure demonstrates that at no step the top diagonal pivot element of consecutive sub-matrices can be zero. To avoid it columns or rows may be swapped so that becomes nonzero.Such procedure involving permutation is calledLUP, decomposition with pivoting.
Permutation of columns corresponds to matrix product where is a permutation matrix, i.e. the identity matrix after the same column permutation. After all steps such LUP decomposition applies to. Present computation scheme and similar in Cormen et al.[2] are examples ofrecurrence algorithms. They demonstrate two general properties of LU factorization:
Recurrence algorithms are not overly costly in terms of algebraic operations yet they suffer from practical disadvantage due to need to update and store most elements ofA at each step. It will be seen that by reordering calculations it is possible to dispose with storage of intermediate values.
It turns out that a proper permutation of rows (or columns) to select column (or row) absolute maximal pivota11 is sufficient for numerically stable LU factorization, except for known pathological cases. It is calledLU factorization with partial pivoting (LUP):whereL andU are again lower and upper triangular matrices, andP andQ are correspondingpermutation matrices, which, when correspondingly left- and right-multiplied toA, reorder the rows and columns ofA. It turns out that all square matrices can be factorized in this form,[3] and the factorization is numerically stable in practice.[4] This makes LUP decomposition a useful technique in practice.
A variant calledrook pivoting at each step involves search of maximum element the way rook moves on a chessboard, along column, row, column again and so on till reaching a pivot maximal in both its row and column. It can be proven that for large matrices of random elements its cost of operations at each step is similarly to partial pivoting proportional to the length of matrix side unlike its square for full pivoting.
AnLU factorization with full pivoting involves both row and column permutations to find absolute maximum element in the whole submatrix:whereL,U, andP are defined as before, andQ is a permutation matrix that reorders the columns ofA.[5]
Alower-diagonal-upper decomposition (LDU) is a decomposition of the formwhereD is adiagonal matrix, andL andU areunitriangular matrices, meaning that all the entries on the diagonals ofL andU are one.
Above we required thatA be a square matrix, but these decompositions can all be generalized to rectangular matrices as well.[6] In that case,L andD are square matrices both of which have the same number of rows asA, andU has exactly the same dimensions asA. 'Upper triangular' should be interpreted as having only zero entries below the main diagonal, which starts at the upper left corner. Similarly, the more precise term forU is that it is therow echelon form of the matrixA.
We factor the following2 × 2 matrix:
One way to find the LU decomposition of this simple matrix would be to simply solve the linear equations by inspection. Expanding thematrix multiplication gives
This system of equations isunderdetermined. In this case any two nonzero elements ofL andU matrices are parameters of the solution and can be set arbitrarily to any nonzero value. Therefore, to find the unique LU decomposition, it is necessary to put some restriction onL andU matrices. For example, we can conveniently require the lower triangular matrixL to be a unit triangular matrix, so that all the entries of its main diagonal are set to one. Then the system of equations has the following solution:
Substituting these values into the LU decomposition above yields
Any square matrixA admits LUP and PLU factorizations.[3] IfA isinvertible, then it admits an LU (or LDU) factorization if and only if all its leading principalminors are nonzero[7][8] (for example does not admit an LU or LDU factorization). IfA is asingular matrix of rankk, then it admits an LU factorization if the firstk leading principal minors are nonzero, although the converse is not true.[9]
If a square, invertible matrix has an LDU factorization (with all diagonal entries ofL andU equal to1), then the factorization is unique.[8] In that case, the LU factorization is also unique if we require that the diagonal of eitherL orU consists of ones.
In general, any square matrixAn×n could have one of the following:
In Case 3, one can approximate an LU factorization by changing a diagonal entryaij toaij ±ε to avoid a zero leading principal minor.[10]
IfA is a symmetric (orHermitian, ifA is complex)positive-definite matrix, we can arrange matters so thatU is theconjugate transpose ofL. That is, we can writeA as
This decomposition is called theCholesky decomposition. IfA is positive definite, then the Cholesky decomposition exists and is unique. Furthermore, computing the Cholesky decomposition is more efficient andnumerically more stable than computing some other LU decompositions.
For a (not necessarily invertible) matrix over any field, the exact necessary and sufficient conditions under which it has an LU factorization are known. The conditions are expressed in terms of the ranks of certain submatrices. The Gaussian elimination algorithm for obtaining LU decomposition has also been extended to this most general case.[11]
When an LDU factorization exists and is unique, there is a closed (explicit) formula for the elements ofL,D, andU in terms of ratios of determinants of certain submatrices of the original matrixA.[12] In particular,D1 =A1,1, and fori = 2, ... ,n,Di is the ratio of thei-th principal submatrix to the(i − 1)-th principal submatrix. Computation of the determinants iscomputationally expensive, so this explicit formula is not used in practice.
The following algorithm is essentially a modified form ofGaussian elimination. Computing an LU decomposition using this algorithm requires2/3n3 floating-point operations, ignoring lower-order terms. Partialpivoting adds only a quadratic term; this is not the case for full pivoting.[13]
Given anN × N matrix, define as the original, unmodified version of the matrixA. The parenthetical superscript (e.g.,(0)) of the matrixA is the version of the matrix. The matrixA(n) is theA matrix in which the elements below themain diagonal have already been eliminated to 0 through Gaussian elimination for the firstn columns.
Below is a matrix to observe to help us remember the notation (where each∗ represents anyreal number in the matrix):
During this process, we gradually modify the matrixA using row operations until it becomes the matrixU in which all the elements below the main diagonal are equal to zero. During this, we will simultaneously create two separate matricesP andL, such thatPA =LU.
We define the finalpermutation matrixP as the identity matrix which has all the same rows swapped in the same order as theA matrix while it transforms into the matrixU. For our matrixA(n−1), we may start by swapping rows to provide the desired conditions for then-th column. For example, we might swap rows to perform partial pivoting, or we might do it to set the pivot elementan,n on the main diagonal to a nonzero number so that we can complete the Gaussian elimination.
For our matrixA(n−1), we want to set every element below to zero (where is the element in then-th column of the main diagonal). We will denote each element below as (wherei =n+1, ... ,N). To set to zero, we setrowi =rowi − (ℓi,n)⋅rown for each rowi. For this operation,. Once we have performed the row operations for the firstN − 1 columns, we have obtained anupper triangular matrixA(N−1) which is denoted byU.
We can also create thelower triangular matrix denoted asL, by directly inputting the previously calculated values ofℓi,n via the formula below.
If we are given the matrixwe will choose to implement partial pivoting and thus swap the first and second row so that our matrixA and the first iteration of ourP matrix respectively becomeOnce we have swapped the rows, we can eliminate the elements below the main diagonal on the first column by performingsuch that,Once these rows have been subtracted, we have derived fromA(1) the matrix
Because we are implementing partial pivoting, we swap the second and third rows of our derived matrix and the current version of ourP matrix respectively to obtainNow, we eliminate the elements below the main diagonal on the second column by performingrow3 =row3 − (ℓ3,2)⋅row2 such thatℓ3,2 =5/6. Because no nonzero elements exist below the main diagonal in our current iteration ofA after this row subtraction, this row subtraction derives our finalA matrix (denoted asU) and finalP matrix:After also switching the corresponding rows, we obtain our finalL matrix:
Now these matrices have a relation such thatPA =LU.
If we did not swap rows at all during this process, we can perform the row operations simultaneously for each columnn by setting where is theN × N identity matrix with itsn-th column replaced by thetransposed vector(0 ⋯ 0 1 −ℓn+1,n ⋯ −ℓN,n)T.
In other words, the lower triangular matrix
Performing all the row operations for the firstN − 1 columns using the formula is equivalent to finding the decompositionDenoteL =L1 ⋯LN−1 so thatA =LA(N−1) =LU.
Now let's compute the sequence ofL1 ⋯LN−1. We know thatLi has the following formula:
If there are two lower triangular matrices with 1s in the main diagonal, and neither have a nonzero item below the main diagonal in the same column as the other, then we can include all nonzero items at their same location in the product of the two matrices. For example:
Finally, multiplyL1 together and generate the fused matrix denoted asL (as previously mentioned). Using the matrixL, we obtainA =LU.
It is clear that in order for this algorithm to work, one needs to have at each step (see the definition ofℓi,n. If this assumption fails at some point, one needs to interchangen-th row with another row below it before continuing. This is why an LU decomposition in general looks likeP−1A =LU.

Although Banachiewicz (1938) LU decomposition algorithm preceded the advent of programmed electronic computers, it wasready made for direct implementation into code as index swapping, transpose and column by column multiplication remain native built capabilities of the most programming languages and they are handled by compilers alone with little delay of the actual execution. The peculiar matrix notation used by Banachiewicz enabled him to multiply matrices column by column, a convenient feature for mechanical calculations as he could reveal consecutive factors by sliding a ruler to next rows of matrices. For human readers however, his equations are best transformed into standard matrix notation. To obtain from a full matrixA triangle matricesU andL calculations, start by copying top row and leftmost column ofA respectively into corresponding positions of matricesU andL. The known unit diagonal elements ofL are not stored nor used throughout the whole process.Next calculations continue for the subsequent rows and columns till the bottom right corner ofA.
The figure illustrates calculations for 3rd row and column, assuming previous stages were already completed. Involved matrices are named above squares marking their content. Matrix products and subtractions are applied only to elements in the thick frame boxes.Green filled thin frame boxes indicate values already known, from previous stages. Blue boxes indicate places inU andL matrices for storing of results. Note that at each stage the result elements ofL need to be divided by the corresponding pivot element on the main diagonal ofU. This applies to the leftmost column ofL too.
Note that after completion of 3rd stage the involved elements of matrixA are no longer used and neither those from the previous stages. This enables replacement of these elements with the result values ofU andL, i.e. execution of LU decompositionin place, so that the wholeA is replaced withU andL except for the unit diagonal ofL. Banachiewicz LU algorithm is well suited for partial pivoting by choosing the absolute maximum pivot from the newly calculated row ofU and subsequently swapping its columns so that it lands on the main diagonal. More details can be figured out from inspection of the enclosed Fortran90 code.
All partial pivoting LU algorithms cost roughly the same amount, of order operations, wheren is the number of rows or columns ofA.
Note that the decomposition obtained through this procedure is aDoolittle decomposition: the main diagonal ofL is composed solely of ones. If one would proceed by removing elementsabove the main diagonal by adding multiples of thecolumns (instead of removing elementsbelow the diagonal by adding multiples of therows), we would obtain aCrout decomposition, where the main diagonal ofU is of ones.
Another (equivalent) way of producing a Crout decomposition of a given matrixA is to obtain a Doolittle decomposition of the transpose ofA. Indeed, ifAT =L0U0 is the LU-decomposition obtained through the algorithm presented in this section, then by takingL =UT
0 andU =LT
0, we have thatA =LU is a Crout decomposition.
It is possible to find a low rank approximation to an LU decomposition using arandomized algorithm. Given an input matrixA and a desired low rankk, the randomized LU returns permutation matricesP,Q and lower/upper trapezoidal matricesL,U of sizem × k andk × n respectively, such that with high probability‖PAQ −LU‖2 ≤Cσk+1, whereC is a constant that depends on the parameters of the algorithm andσk+1 is the(k+1)-th singular value of the input matrixA.[14]
If two matrices of ordern can be multiplied in timeM(n), whereM(n) ≥na for somea > 2, then an LU-decomposition can be computed in timeO(M(n)).[15] This means, for example, that anO(n2.376) algorithm exists based on theCoppersmith–Winograd algorithm.
Special algorithms have been developed for factorizing largesparse matrices. These algorithms attempt to find sparse factorsL andU. Ideally, the cost of computation is determined by the number of nonzero entries, rather than by the size of the matrix.
These algorithms use the freedom to exchange rows and columns to minimize fill-in (entries that change from an initial zero to a nonzero value during the execution of an algorithm).
General treatment of orderings that minimize fill-in can be addressed usinggraph theory.
Given a system of linear equations in matrix form
we want to solve the equation forx, givenA andb. Suppose we have already obtained the LUP decomposition ofA such thatPA =LU, soLUx =Pb.
In this case the solution is done in two logical steps:
In both cases we are dealing with triangular matrices (L andU), which can be solved directly byforward and backward substitution without using theGaussian elimination process (however we do need this process or equivalent to compute the LU decomposition itself).
The above procedure can be repeatedly applied to solve the equation multiple times for differentb. In this case it is faster (and more convenient) to do an LU decomposition of the matrixA once and then solve the triangular matrices for the differentb, rather than using Gaussian elimination each time. The matricesL andU could be thought to have "encoded" the Gaussian elimination process.
The cost of solving a system of linear equations is approximately2/3n3 floating-point operations if the matrixA has sizen. This makes it twice as fast as algorithms based onQR decomposition, which costs about4/3n3 floating-point operations whenHouseholder reflections are used. For this reason, LU decomposition is usually preferred.[16]
When solving systems of equations,b is usually treated as a vector with a length equal to the height of matrixA. In matrix inversion however, instead of vectorb, we have matrixB, whereB is ann × p matrix, so that we are trying to find a matrixX (also an × p matrix):
We can use the same algorithm presented earlier to solve for each column of matrixX. Now suppose thatB is the identity matrix of sizen,In. It follows that the resultX must be the inverse ofA.[17]
Given the LUP decompositionA =P−1LU of a square matrixA, the determinant ofA can be computed straightforwardly as
The second equation follows from the fact that the determinant of a triangular matrix is simply the product of its diagonal entries, and that the determinant of a permutation matrix is equal to(−1)S whereS is the number of row exchanges in the decomposition.
In the case of LU decomposition with full pivoting,det(A) also equals the right-hand side of the above equation, if we letS be the total number of row and column exchanges.
The same method readily applies to LU decomposition by settingP equal to the identity matrix.

The LU decomposition is related to elimination of linear systems of equations, as e.g. described by Ralston.[18] The solution ofN linear equations inN unknowns by elimination was already known to ancient Chinese.[19] Before Gauss many mathematicians in Eurasia were performing and perfecting it yet as the method became relegated to school grade, few of them left any detailed descriptions. Thus the name Gaussian elimination is only a convenient abbreviation of a complex history.
The Polish astronomer Tadeusz Banachiewicz introduced the LU decomposition in 1938.[1] About Banachiewicz, Paul Dwyer stated:[20][page needed]
It appears that Gauss and Doolittle applied the method [of elimination] only to symmetric equations. More recent authors, for example, Aitken, Banachiewicz, Dwyer, and Crout ... have emphasized the use of the method, or variations of it, in connection with non-symmetric problems ... Banachiewicz ... saw the point ... that the basic problem is really one of matrix factorization, or "decomposition" as he called it.
— Paul Dwyer,Linear Computations (1951)
Banachiewicz[1] was the first to consider elimination in terms of matrices and in this way formulated LU decomposition, as demonstrated by his graphic illustration. His calculations follow ordinary matrix ones, yet notation deviates in that he preferred to write one factor transposed, to be able to multiply them mechanically column by column, by sliding ruler down consecutive rows of both (usingarithmometer). Combined with swapped order of indices his formulae in modern notation read
whereIA →AT;x ≡ [x1, ... ,xn, −1];A′ refers toA extended with the last column; and the last component ofx is−1. Matrix formulae to calculate rows and columns of LU factors by recursion are given in the remaining part of Banachiewicz's paper as Eq. (2.3) and (2.4)(see§ Fortran90 code example below). This paper by Banachiewicz contains both derivation ofLU andRTR factors of respectively non-symmetric and symmetric matrices. They are sometimes confused as later publications tend to tie his name solely with the rediscovery of Cholesky decomposition. Banachiewicz himself can be excused of inaction as already next year he suffered from persecution by occupiers, spending three month inthe Sachsenhausen Concentration Camp, on release from which he carried himself from a train his collaborator and co-prisoner Antoni Wilk, who died of exhaustion a week later.
ModulemluImplicit NoneInteger,Parameter::SP=Kind(1d0)! set I/O real precisionPrivate Publicluban,lusolveContains Subroutineluban(a,tol,g,h,ip,condinv,detnth)! By Banachiewicz (1938, hereafter B38) LU decomposition method calculates such! triangles L=G^T, and U=H that square B=A^T=G^TH=LU. Partial pivoting! by column permutation IP(:) is modern addition.! Within the code a, g correspond to B38 A^T and G^T, so that a=gh holds.!! Normal use is for square A, however for RHS l already known! input of (A|l)^T yields (L|y^T)^T where x in L^Tx=y is solution of Ax=l.Real(SP),Intent(In)::a(:,:)! input matrix A(m,n), n<=mReal(SP),Intent(In)::tol! tolerance for near zero pivotReal(SP),Intent(Out)::g(size(a,dim=1),size(a,dim=2))! L(m,n)Real(SP),Intent(Out)::h(size(a,dim=2),size(a,dim=2))! U(n,n)! note U columns are permutedReal(SP),Intent(Out)::condinv! 1/cond(A), 0 for singular AReal(SP),Intent(Out)::detnth! sign*Abs(det(A))**(1/n)Integer,Intent(Out)::ip(size(a,dim=2))! columns permutation!Integer::k,n,j,l,isigReal(SP)::tol0,pivmax,pivmin,piv!n=size(a,dim=2)tol0=Max(tol,3._SP*epsilon(tol0))! use default for tol=0!! Rectangular A and G are permitted under condition:If(n>size(a,dim=1).Or.n<1)Stop91Forall(k=1:n)ip(k)=kh=0._SPg=0._SPisig=1detnth=0._SPpivmax=Maxval(Abs(a(1,:)))pivmin=pivmax!Dok=1,n! Banachiewicz (1938) Eq. (2.3)h(k,ip(k:))=a(k,ip(k:))-Matmul(g(k,:k-1),h(:k-1,ip(k:)))!! Find row pivotj=(Maxloc(Abs(h(k,ip(k:))),dim=1)+k-1)If(j/=k)Then! Swap columns j and kisig=-isig! Change Det(A) sign because of permutationl=ip(k)ip(k)=ip(j)ip(j)=lEnd Ifpiv=Abs(h(k,ip(k)))pivmax=Max(piv,pivmax)! Adjust condinvpivmin=Min(piv,pivmin)If(piv<tol0)Then! singular matrixisig=0pivmax=1._SPExit Else! Account for pivot contribution to Det(A) sign and valueIf(h(k,ip(k))<0._SP)isig=-isigdetnth=detnth+Log(piv)End If!! Transposed Banachiewicz (1938) Eq. (2.4)g(k+1:,k)=(a(k+1:,ip(k))-&Matmul(g(k+1:,:k-1),h(:k-1,ip(k))))/h(k,ip(k))g(k,k)=1._SPEnd Do!detnth=isig*Exp(detnth/n)condinv=Abs(isig)*pivmin/pivmax! Test for square A(n,n) by uncommenting below! Print *, '|AQ-LU| ',Maxval (Abs(a(:,ip(:))-Matmul(g, h(:,ip(:)))))End SubroutinelubanSubroutinelusolve(l,u,ip,x)! Solves Ax=b system using triangle factors LU=AReal(SP),Intent(In)::l(:,:)! lower triangle matrix L(n,n)Real(SP),Intent(In)::u(:,:)! upper triangle matrix U(n,n)Integer,Intent(In)::ip(:)! columns permutation IP(n)Real(SP),Intent(InOut)::x(:,:)! Input: m sets of RHSs B(n,m),! Output: the corresponding sets of unknowns X(n,m)Integer::n,m,i,jn=size(ip)m=size(x,dim=2)If(n<1.Or.m<1.Or.Any([n,n]/=shape(l)).Or.Any(shape(l)/=shape(u)).Or.&n/=size(x,dim=1))Stop91Doi=1,mDoj=1,nx(j,i)=x(j,i)-dot_product(x(:j-1,i),l(j,:j-1))End Do Doj=n,1,-1x(j,i)=(x(j,i)-dot_product(x(j+1:,i),u(j,ip(j+1:))))/&u(j,ip(j))End Do End Do End SubroutinelusolveEnd Modulemlu
/* INPUT: A - array of pointers to rows of a square matrix having dimension N * Tol - small tolerance number to detect failure when the matrix is near degenerate * OUTPUT: Matrix A is changed, it contains a copy of both matrices L-E and U as A=(L-E)+U such that P*A=L*U. * The permutation matrix is not stored as a matrix, but in an integer vector P of size N+1 * containing column indexes where the permutation matrix has "1". The last element P[N]=S+N, * where S is the number of row exchanges needed for determinant computation, det(P)=(-1)^S */intLUPDecompose(double**A,intN,doubleTol,int*P){inti,j,k,imax;doublemaxA,*ptr,absA;for(i=0;i<=N;i++)P[i]=i;//Unit permutation matrix, P[N] initialized with Nfor(i=0;i<N;i++){maxA=0.0;imax=i;for(k=i;k<N;k++)if((absA=fabs(A[k][i]))>maxA){maxA=absA;imax=k;}if(maxA<Tol)return0;//failure, matrix is degenerateif(imax!=i){//pivoting Pj=P[i];P[i]=P[imax];P[imax]=j;//pivoting rows of Aptr=A[i];A[i]=A[imax];A[imax]=ptr;//counting pivots starting from N (for determinant)P[N]++;}for(j=i+1;j<N;j++){A[j][i]/=A[i][i];for(k=i+1;k<N;k++)A[j][k]-=A[j][i]*A[i][k];}}return1;//decomposition done}/* INPUT: A,P filled in LUPDecompose; b - rhs vector; N - dimension * OUTPUT: x - solution vector of A*x=b */voidLUPSolve(double**A,int*P,double*b,intN,double*x){for(inti=0;i<N;i++){x[i]=b[P[i]];for(intk=0;k<i;k++)x[i]-=A[i][k]*x[k];}for(inti=N-1;i>=0;i--){for(intk=i+1;k<N;k++)x[i]-=A[i][k]*x[k];x[i]/=A[i][i];}}/* INPUT: A,P filled in LUPDecompose; N - dimension * OUTPUT: IA is the inverse of the initial matrix */voidLUPInvert(double**A,int*P,intN,double**IA){for(intj=0;j<N;j++){for(inti=0;i<N;i++){IA[i][j]=P[i]==j?1.0:0.0;for(intk=0;k<i;k++)IA[i][j]-=A[i][k]*IA[k][j];}for(inti=N-1;i>=0;i--){for(intk=i+1;k<N;k++)IA[i][j]-=A[i][k]*IA[k][j];IA[i][j]/=A[i][i];}}}/* INPUT: A,P filled in LUPDecompose; N - dimension. * OUTPUT: Function returns the determinant of the initial matrix */doubleLUPDeterminant(double**A,int*P,intN){doubledet=A[0][0];for(inti=1;i<N;i++)det*=A[i][i];return(P[N]-N)%2==0?det:-det;}
publicclassSystemOfLinearEquations{publicdouble[]SolveUsingLU(double[,]matrix,double[]rightPart,intn){// decomposition of matrixdouble[,]lu=newdouble[n,n];doublesum=0;for(inti=0;i<n;i++){for(intj=i;j<n;j++){sum=0;for(intk=0;k<i;k++)sum+=lu[i,k]*lu[k,j];lu[i,j]=matrix[i,j]-sum;}for(intj=i+1;j<n;j++){sum=0;for(intk=0;k<i;k++)sum+=lu[j,k]*lu[k,i];lu[j,i]=(1/lu[i,i])*(matrix[j,i]-sum);}}// lu = L+U-I// find solution of Ly = bdouble[]y=newdouble[n];for(inti=0;i<n;i++){sum=0;for(intk=0;k<i;k++)sum+=lu[i,k]*y[k];y[i]=rightPart[i]-sum;}// find solution of Ux = ydouble[]x=newdouble[n];for(inti=n-1;i>=0;i--){sum=0;for(intk=i+1;k<n;k++)sum+=lu[i,k]*x[k];x[i]=(1/lu[i,i])*(y[i]-sum);}returnx;}}
functionLU=LUDecompDoolittle(A)n=length(A);LU=A;fork=2:nfori=1:k-1lamda=LU(k,i)/LU(i,i);LU(k,i)=lamda;LU(k,i+1:n)=LU(k,i+1:n)-LU(i,i+1:n)*lamda;endendendfunctionx=SolveLinearSystem(LU, B)n=length(LU);y=zeros(size(B));% find solution of Ly = Bfori=1:ny(i,:)=B(i,:)-LU(i,1:i)*y(1:i,:);end% find solution of Ux = yx=zeros(size(B));fori=n:(-1):1x(i,:)=(y(i,:)-LU(i,(i+1):n)*x((i+1):n,:))/LU(i,i);endendA=[433;633;343]LU=LUDecompDoolittle(A)B=[123;456;789;101112]'x=SolveLinearSystem(LU,B)A*x
References
Computer code
Online resources