← LibraryComputing the Inverse of a MatrixEngineering · Engineering MathematicsLesson 175/812← PrevNext →
ArticlePublished 7 Aug 2026Updated 9 Aug 202621 min readBy KEVOS®
Skip to content

Engineering/Mathematics/Matrices

Computing the Inverse of a Matrix

The inverse of a nonsingular matrix A is obtained by row-reducing the augmented array [AIn] until the left block becomes In; the right block is then A1. The method works because inverting a matrix is nothing more than solving n linear systems that share a coefficient matrix.

  • Core level
  • Stream: computation
  • Reading time 14 min
  • Ref KVS-ENG-MATH-0043
Taxonomy
Engineering / Mathematics
Prerequisite
Gauss-Jordan elimination and the matrix inverse
Method
Row-reduce [AIn] to [InA1]
Cost
About 2n3 floating-point operations
Failure signal
Left block does not reduce to In
Shortcut
2×2 closed formula using adbc

Overview

Knowing that an inverse exists is a different problem from producing one. The naive route — write n2 unknown entries, impose AB=In, and solve the resulting n2 equations — is workable for 2×2 matrices and yields a memorable closed formula, but it collapses under its own notation almost immediately afterwards. A 3×3 attempt already requires eighteen symbols.

The productive reformulation is to think in columns. Matrix multiplication acts column by column, so the single matrix equation AB=In splits into n independent vector equations ABj=ej, one for each column of the unknown B and each standard unit vector on the right. Every one of these is an ordinary linear system, and crucially they all share the coefficient matrix A. Column j of the inverse is simply the solution of the j-th system.

Solving those n systems separately would repeat the identical sequence of row operations n times. Gauss-Jordan reduction of the single augmented array [AIn] performs the work once and carries all n right-hand sides along simultaneously. When the left block reduces to In, each of the n systems has been solved and the answers are stacked side by side in the right block. When the left block does not reduce to In — a zero row appears — the matrix is singular and the procedure correctly reports that no inverse exists.

The same augmented array is also a record of the elimination itself. Row reduction is left multiplication by a product of elementary matrices, so reducing [AIn] produces [JAJ] where J accumulates that product. If JA=In then J is the inverse, which is why the identity block is the right thing to append: it starts as a blank ledger and finishes holding the entire transformation.

Definition

Standard Unit Vectors

SUV

For each j with 1jm, the vector ejm is column j of the identity matrix Im: it has a 1 in position j and 0 everywhere else. The collection {e1,e2,,em} is the set of standard unit vectors in m.

Entrywise, [ej]i=1 when i=j and 0 otherwise. These vectors are the natural right-hand sides for the inversion problem because they are exactly the columns of In.

Two-by-Two Matrix Inverse

TTMI

For A=[abcd], the matrix A is invertible if and only if adbc0, and in that case A1=1adbc[dbca].

The quantity adbc is the determinant of A. The forward implication is a direct verification; the converse is proved by contradiction, multiplying rather than dividing so that no entry has to be assumed non-zero.

Computing the Inverse of a Nonsingular Matrix

CINSM

Let A be a nonsingular square matrix of size n. Form the n×2n array M=[AIn], let N be the matrix row-equivalent to M that is in reduced row-echelon form, and let J consist of the final n columns of N. Then AJ=In.

The statement delivers a right inverse. Because A is square, the reverse product JA=In follows as well, so J=A1; that step requires a separate theorem and should not be assumed silently.

Concepts

Inversion is n linear systems in disguise

Write the unknown inverse as B=[B1B2Bn]. Because AB=[AB1AB2ABn], the condition AB=In is equivalent to the n separate systems ABj=ej. This is the conceptual pivot of the whole subject: a matrix problem becomes n vector problems, all sharing one coefficient matrix, and sharing a coefficient matrix is precisely the situation elimination is designed to exploit.

Why the identity block is the right thing to append

Each elementary row operation is realised by left multiplication with an elementary matrix. Reducing [AIn] therefore produces [EkE2E1AEkE2E1]. Setting J=EkE1, the array is [JAJ]. The reduction stops when JA is in reduced row-echelon form; if that form is In, then J is a left inverse of A and the right block has recorded it. The identity block functions as an audit trail of the elimination.

The two-by-two formula and why it does not generalise

For a 2×2 matrix the four unknown entries can be eliminated by hand, giving A1=(adbc)1[dbca]: swap the diagonal, negate the off-diagonal, divide by the determinant. A general closed formula does exist for size n — the adjugate divided by the determinant — but it involves n2 determinants of size n1 and its cost grows factorially. Row reduction is polynomial. The closed formula is a theoretical instrument; elimination is the working method.

What the procedure does when the matrix is singular

If A is singular, its reduced row-echelon form has a zero row and cannot be In. Row reduction of [AIn] still terminates, but the left block ends in a form with fewer than n leading ones and the right block is not an inverse of anything. This is a genuine diagnosis rather than a breakdown: the procedure has demonstrated that at least one of the systems Ax=ej is inconsistent, so no matrix B can satisfy AB=In.

One-sided output and the missing half

The reduction argument establishes AJ=In directly, because column n+i of the reduced array solves the i-th system. It does not by itself establish JA=In, which the definition of the inverse also demands. For square matrices the second identity is automatic, but that is a theorem in its own right. Until it is invoked, the honest statement is that the procedure yields a right inverse of a nonsingular matrix.

Pivoting choices affect the arithmetic, not the answer

Reduced row-echelon form is unique, so the computed inverse does not depend on the order in which pivots were chosen. That freedom is exploited differently in exact and inexact arithmetic: by hand, a row with a leading 1 is promoted first to keep fractions out of the early stages, whereas in floating point the row with the largest pivot magnitude is chosen to limit growth of rounding error. Both routes terminate at the same A1.

Procedure: inverting a square matrix by row reduction

Append the identityForm the n×2n array M=[AIn], keeping the two blocks aligned.
Reduce the whole arrayApply Gauss-Jordan elimination to M, operating on all 2n entries of every row. Never treat the blocks separately.
Inspect the left blockIf the left block is In, continue. If a zero row appears, A is singular; stop and report that no inverse exists.
Read off the candidateExtract the final n columns as J. The construction guarantees AJ=In.
VerifyConfirm JA=In as well, or invoke the one-sided inverse theorem. Record A1=J.

Equations

Entries of a standard unit vector

EQ-CIM-01
[ej]i={1i=j0ij

The vector ej is column j of Im, and the collection of all of them is the set of standard unit vectors.

Column-by-column form of the inversion problem

EQ-CIM-02
A[B1B2Bn]=[e1e2en]ABj=ej,1jn

Matrix multiplication acts column by column, so one matrix equation is exactly n vector equations with a shared coefficient matrix.

Closed formula for a two-by-two inverse

EQ-CIM-03
A=[abcd]A1=1adbc[dbca],adbc0

Swap the diagonal entries, negate the off-diagonal entries, divide by the determinant. The matrix is invertible precisely when adbc0.

The augmented inversion array

EQ-CIM-04
[AIn][InA1]

Row-equivalence of the two arrays, valid exactly when A is nonsingular. The symbol denotes row equivalence.

Row reduction as left multiplication

EQ-CIM-05
J=EkE2E1,[AIn][JAJ]

Each Ei is the elementary matrix of one row operation. The appended identity block accumulates the product, so the transformation is recorded as it is applied.

Conclusion of the reduction procedure

EQ-CIM-06
JA=InAJ=InA1=J

The first implication is the one-sided inverse theorem for square matrices; without it the procedure delivers only a one-sided inverse.

Worked blending matrix and its inverse

EQ-CIM-07
A=[312121213],A1=18[513151315]

The example carried through below. Note that the inverse of a symmetric matrix is symmetric, a useful check on the arithmetic.

Variable Definitions

Symbols used on this page
SymbolNameMeaningDomain / type
AMatrix to be invertedSquare matrix of size n, assumed nonsingular for the procedure to succeedn x n complex matrix
MAugmented arrayThe n×2n array [AIn] presented to the reductionn x 2n matrix
NReduced arrayThe reduced row-echelon form of Mn x 2n matrix
JRight-hand blockFinal n columns of N; equals A1 when the left block is Inn x n matrix
ejStandard unit vectorColumn j of In; the right-hand side of the j-th systemC^n
BjColumn j of the unknown inverseThe unique solution of Ax=ejC^n
EiElementary matrixThe matrix implementing one elementary row operation by left multiplicationn x n matrix
adbcTwo-by-two determinantScalar whose vanishing characterises singularity of a 2×2 matrixcomplex scalar
nSizeCommon row and column count of Apositive integer

Worked Numerical Example

Problem statement

Three ore concentrates are blended to hit a specified metal assay. Column j of the assay matrix A gives the content of the three target metals in concentrate j, in consistent units. Invert A once so that any future assay target can be converted directly into a blend recipe.

  1. Form the augmented array

    Place the 3×3 identity to the right of the assay matrix. Every subsequent row operation acts on all six entries of a row.

    M=[312100121010213001]
  2. Promote a convenient pivot

    Row 2 already has a leading 1 in column 1. Exchanging rows 1 and 2 avoids introducing thirds at the very first step. Exact arithmetic permits this choice freely, because the reduced form is unique.

    [121010312100213001]
  3. Clear the first column

    Apply R2R23R1 and R3R32R1. The right block is no longer the identity; it is accumulating the transformation.

    [121010051130031021]
  4. Normalise and clear the second column

    Scale with R215R2 to obtain a leading 1, then clear above and below using R1R12R2 and R3R3+3R2.

    [103525150011515350008535151]
  5. Normalise and clear the third column

    Scale with R358R3, then apply R1R135R3 and R2R215R3. The left block is now I3, which confirms that A is nonsingular.

    [100581838010185818001381858]
  6. Extract and verify the inverse

    The right block is the candidate inverse. Its symmetry mirrors the symmetry of A, which is one free check. A second check multiplies row 1 of A into column 1 of the candidate: 18(35+1(1)+2(3))=18(1516)=1, as required.

    A1=18[513151315]
  7. Convert an assay target into a recipe

    A target assay of b=(7,6,7) gives blend proportions x=A1b. The first entry is 18(35621)=1, the second is 18(7+307)=2, the third is 18(216+35)=1.

    x=A1[767]=[121]
  8. Contrast with a singular assay matrix

    Had the third concentrate been a fixed dilution of the second — say column 3 equal to 2 times column 2 — the left block would have finished with a zero row. That is not an arithmetic failure but a physical statement: the three concentrates would span only a two-dimensional set of achievable assays, and most targets would be unreachable by any blend.

Result

One reduction produces A1 in exact rational form, after which every future assay target costs a single matrix-vector product rather than a fresh elimination. The verified target (7,6,7) corresponds to blending the concentrates in the ratio 1:2:1. Because A is nonsingular, each achievable assay corresponds to exactly one recipe, and negative entries in a computed recipe would signal a target outside the physically attainable region.

Applications & Industry Use

Mineral processing

Blend recipes from assay targets

With feedstock compositions as columns of A, the inverse converts any required product assay into the blend proportions that achieve it. Inverting once and reusing the result suits a plant that re-specifies its target grade several times a shift while the feed sources remain unchanged.

Instrumentation and metrology

Sensor cross-talk decoupling

A multi-axis load cell or magnetometer produces raw channel readings related to true axis values by a calibration matrix determined during commissioning. Inverting that matrix once yields the decoupling matrix stored in firmware, so each measurement is corrected by a single matrix-vector product at sample rate.

Colour science and printing

Device colour transforms

Converting between an RGB primary set and CIE XYZ tristimulus coordinates uses a 3×3 matrix built from the primaries and white point. The reverse transform is its inverse, computed once at profile creation and embedded in the colour management pipeline.

Chemical engineering

Reactor recycle and species balances

Steady-state species balances around a recycle loop give a square linear system in the unknown stream compositions. When the same flowsheet is evaluated across many feed conditions, an explicit inverse of the balance matrix turns each case into a multiplication rather than a re-solve.

Cryptography

Key inversion over a finite field

Classical matrix ciphers encrypt blocks by multiplication with a key matrix over the integers modulo m. Decryption requires the inverse over that modulus, obtained by the same augmented reduction with modular arithmetic, and the key is admissible only when its determinant is a unit modulo m.

Geotechnical engineering

Back-analysis of soil parameters

A linearised model relating measured settlements to unknown stiffness parameters yields a square coefficient matrix. Inverting it exposes how strongly each measurement constrains each parameter, and near-singularity is the quantitative warning that the instrumentation layout cannot separate two parameters.

Design Considerations

Reduce the array as a unit

Every row operation must be applied across all 2n entries of the row. Operating on the left block alone silently destroys the correspondence between the accumulated transformation and the matrix it transforms, and the resulting right block is not an inverse of anything. This is the single most common procedural error in hand computation.

Pick pivots for the arithmetic you are doing

In exact arithmetic, promote a row whose leading entry is 1 or a small integer to keep fractions manageable; the destination is unaffected because the reduced form is unique. In floating point, choose the largest available pivot magnitude in the column, because partial pivoting bounds the growth of the multipliers and hence of rounding error.

Prefer a factorisation unless the inverse itself is required

If the goal is to solve Ax=b for a handful of right-hand sides, an LU factorisation with triangular solves is cheaper and more accurate. Compute the explicit inverse when its entries are the deliverable — a decoupling matrix, a covariance, a set of influence coefficients — or when the number of right-hand sides is comparable to n.

Exploit structure before calling a general routine

Diagonal, triangular, orthogonal, unitary and permutation matrices all invert far more cheaply than the general procedure. A permutation matrix inverts by transposition alone. Checking for structure costs O(n2) and can save an O(n3) reduction outright.

Treat near-singularity as a modelling result

A left block that reduces to something very close to In but with a tiny pivot indicates a matrix that is technically invertible and practically useless. Report the condition number rather than the bare inverse; in a calibration or back-analysis context, a huge condition number means the experiment cannot distinguish two effects and the instrumentation, not the arithmetic, needs attention.

Keep an independent check on the result

The symmetry of the inverse of a symmetric matrix, agreement with the closed formula in the 2×2 case, and a spot check of one row-column product all cost far less than the reduction itself. Build one of them into any hand computation as a matter of routine.

Standards & Codes

Notation, interchange and numerical standards that govern how this material is written down, stored and computed in production systems.

Applicable standards, conventions and reference implementations
ReferenceTitleRelevance to this topic
ISO 80000-2Quantities and units — Part 2: MathematicsStandardises the augmented-array notation, the symbol In for the identity matrix and the placement of the inverse exponent used throughout this procedure.
LAPACK / BLAS referenceLinear Algebra PACKage reference implementationImplements inversion as xGETRF followed by xGETRI, that is LU factorisation followed by explicit inversion, rather than as a single Gauss-Jordan sweep, because the factored form is reusable.
IEEE 754-2019IEEE Standard for Floating-Point ArithmeticGoverns the rounding of every division and multiplication in the reduction, and defines the exceptional values that a division by a numerically zero pivot would produce.
BLAS Level 3Basic Linear Algebra Subprograms, matrix-matrix levelBlocked inversion is expressed as matrix-matrix products so that the inner loops run at Level 3 efficiency, which is where nearly all achieved performance in dense inversion comes from.
ISO/IEC 40314Mathematical Markup Language (MathML) Version 3.0Encodes the partitioned arrays on this page with explicit column alignment, so the vertical rule separating the two blocks is semantic rather than decorative.

Material Selection

For a mathematical topic, "material" is the numeric representation: the scalar field, storage format and precision the computation is built from.

Representation and precision selection
RepresentationSelect whenTrade-off
Exact rational arithmeticHand computation, teaching examples and small calibration matrices where an exact inverse must be recorded.Every entry is exactly right and singularity is detected with certainty, but intermediate fractions grow quickly and the method does not scale past a few dozen rows.
Fraction-free integer eliminationInteger matrices where exactness matters but rational blow-up must be contained; the inverse is then reported as an integer matrix over a common determinant denominator.Keeps all intermediates integral and bounded by the Bareiss identity, at the cost of a less familiar algorithm and a deferred final division.
IEEE 754 binary64 (double precision)The default for engineering matrices of moderate size assembled from measured data.Fast and well supported, but a pivot that should be exactly zero appears as a small non-zero value, so singularity becomes a tolerance decision.
IEEE 754 binary32 (single precision)Embedded decoupling matrices and graphics transforms where the matrix is small, fixed and well conditioned.Halves storage and suits GPU pipelines, but about seven significant digits leaves little margin once the condition number exceeds roughly 103.
Fixed-point arithmeticInverse calibration matrices burned into microcontroller firmware without a floating-point unit.Deterministic timing and small code size, but scaling must be designed by hand for every entry and overflow behaviour must be proved rather than assumed.
Modular arithmetic over mBlock ciphers, coding theory and multi-prime reconstruction of an exact rational inverse.Exact with bounded operand size, but invertibility depends on the modulus: the determinant must be a unit, so an otherwise fine matrix can fail for a particular m.

Manufacturing Notes

Implementation notes — how the result is actually produced by hand, by algorithm and by library, including cost and numerical behaviour.

Operation count

Gauss-Jordan reduction of the n×2n array costs about 2n3 floating-point operations. The LU route used by production libraries costs about 23n3 for the factorisation plus a further 43n3 for the inversion of the factors, so the totals are comparable; the LU route wins because the factors can be retained and reused for solves.

Doing it by hand

Work one pivot column at a time, left to right, and never move on until the column is clear both above and below. Write the fractions rather than converting to decimals, so that an exact final answer can be checked. Recording each operation in the margin makes an error traceable instead of forcing a restart.

Library behaviour

NumPy's numpy.linalg.inv and SciPy's scipy.linalg.inv both route through LAPACK's LU-based inversion; SymPy's Matrix.inv() offers Gauss-Jordan, LU and adjugate methods over exact fields. MATLAB's inv issues a warning when the reciprocal condition estimate is below tolerance rather than refusing to return a result.

Detecting singularity in floating point

An exact zero pivot almost never appears in floating-point elimination. Production code therefore compares the reciprocal condition estimate against a tolerance, or examines the smallest singular value, instead of testing a pivot for equality with zero. A singular value decomposition remains the most defensible instrument when the answer matters.

Verification strategy

Compute the residual R=AJIn and check that its norm is small relative to nεAJ. For a symmetric input, verify that the computed inverse is symmetric to within the same tolerance. Both tests are O(n3) and O(n2) respectively and are cheap insurance on any new implementation.

Failure Modes & Common Mistakes

Failure modes, root causes and prevention
Failure mode / mistakeImpactRoot causePrevention & detection
Operating on one block onlyhighApplying a row operation to the left block while forgetting the appended identity, or vice versa.Treat each row of the n×2n array as an indivisible unit; write the vertical rule as a visual reminder rather than a boundary.
Appending the identity on the wrong sidemediumReducing [InA] instead of [AIn], on the assumption that the layout is arbitrary.The matrix being reduced must occupy the leading columns, because it is the one that must become In. Check the layout before the first operation.
Stopping at echelon formhighClearing only below each pivot, so the left block is triangular rather than the identity, and the right block is a partial transformation.Continue until every pivot is the sole non-zero entry in its column. The left block must be exactly In, verified entry by entry.
Declaring an inverse for a singular matrixhighReading off the right block without confirming that the left block reduced to In.Make the identity check an explicit gate in the procedure. A zero row in the left block means no inverse exists, full stop.
Misapplying the 2×2 formulamediumNegating the diagonal and swapping the off-diagonal instead of the reverse, or omitting the division by adbc.State the formula as swap the diagonal, negate the off-diagonal, divide by the determinant, then verify by multiplying out one product.
Dividing by a numerically zero pivothighTesting a floating-point pivot for exact equality with zero, so a value of order 1017 is accepted and amplified.Use partial pivoting with a scaled tolerance, or decide invertibility from a condition estimate or singular values rather than from pivot inspection.
Inverting when a solve was wantedmediumWriting inv(A) @ b in production code out of habit.Use the library solve routine. Reserve explicit inversion for cases where the entries of the inverse are themselves required output.
Losing the sign in a scaling steplowScaling a row by a negative reciprocal such as 15 and applying the sign to only part of the row.Write the scaled row out in full before using it to clear other rows, and confirm the pivot entry is exactly 1.

FAQs

Why does appending the identity matrix work?

Because row reduction is left multiplication by a product of elementary matrices. Reducing [AIn] produces [JAJ] where J is that accumulated product, so when the left block becomes In the right block is exactly the matrix that achieved the reduction — a left inverse of A.

What happens if the matrix is singular?

The left block cannot reduce to In; a zero row appears instead. The procedure has then proved that at least one system Ax=ej is inconsistent, so no matrix can satisfy AB=In. This is a correct diagnosis of non-invertibility, not a breakdown of the method.

Does the answer depend on the order in which I choose pivots?

No. Reduced row-echelon form is unique, so any legal sequence of row operations reaches the same reduced array and hence the same inverse. Pivot order affects only the intermediate arithmetic, which is why it can be chosen for convenience in exact arithmetic and for stability in floating point.

Is there a closed formula for the inverse of an n×n matrix?

Yes: the adjugate matrix divided by the determinant. It is invaluable in proofs and for symbolic 2×2 and 3×3 work, but computing it directly requires n2 determinants of size n1, so its cost is astronomically worse than the polynomial cost of elimination.

Why do libraries use LU factorisation rather than Gauss-Jordan for inversion?

The operation counts are similar, but the LU factors are a reusable asset: they solve any number of later systems at O(n2) each, support determinant and condition estimation, and expose blocked formulations that map onto Level 3 BLAS. Gauss-Jordan produces the inverse and nothing else.

How many arithmetic operations does inverting a matrix cost?

Roughly 2n3 floating-point operations for a dense n×n matrix, against about 23n3 for a factorisation alone. Doubling the size therefore multiplies the work by about eight, which is why explicit inversion becomes untenable well before memory does.

Can I invert a matrix whose entries are unknown symbols?

For small sizes, yes — the 2×2 formula is exactly that. A computer algebra system will carry symbolic elimination further, but expression swell is severe and the result must be qualified by the assumption that every pivot encountered is non-zero, which is a case analysis in disguise.

References

  1. Beezer, R. A. A First Course in Linear Algebra, Version 0.70. University of Puget Sound, 2006. Section MISLE, Subsection CIM. Licensed under the GNU Free Documentation License v1.2.
  2. ISO 80000-2:2019, Quantities and units — Part 2: Mathematics. International Organization for Standardization.
  3. Golub, G. H. and Van Loan, C. F. Matrix Computations, 4th edition. Johns Hopkins University Press, 2013.
  4. Anderson, E. et al. LAPACK Users' Guide, 3rd edition. Society for Industrial and Applied Mathematics, 1999.
  5. Higham, N. J. Accuracy and Stability of Numerical Algorithms, 2nd edition. Society for Industrial and Applied Mathematics, 2002.
  6. IEEE 754-2019, IEEE Standard for Floating-Point Arithmetic. Institute of Electrical and Electronics Engineers.

AI Suggested Questions

  • Show the elementary matrices whose product equals A1 for a specific 3×3 reduction, and confirm the product numerically.
  • Compare the operation counts and measured runtimes of Gauss-Jordan inversion against LU-based inversion for a 1000×1000 matrix.
  • Derive the adjugate formula for a 3×3 inverse and explain why its cost grows factorially with size.
  • How should partial pivoting be organised when the augmented array [AIn] is reduced in floating point?
  • Work through the inversion of a 3×3 matrix modulo 26 and explain when the determinant fails to be a unit.
  • Given a symmetric positive definite matrix, how does a Cholesky-based inversion differ in cost and accuracy from the general method?

Related Calculators

Continue learning

The Inverse of a MatrixArticle · Engineering MathematicsNEXT LESSON →Properties of Matrix InversesArticle · Engineering MathematicsProperties of Matrix MultiplicationArticle · Engineering MathematicsNonsingular Matrices Are InvertibleArticle · Engineering Mathematics