2.6 MATLAB: Inverse of a Square Matrix
In linear algebra the inverse of a square matrix A is a matrix A⁻¹ that satisfies
[ \mathbf{A},\mathbf{A}^{-1}= \mathbf{A}^{-1}\mathbf{A}= \mathbf{I}, ]
where I is the identity matrix. The inverse exists only when A is non‑singular (its determinant is non‑zero) and the matrix is square. MATLAB provides several straightforward ways to obtain the inverse, to check whether an inverse exists, and to handle cases where a true inverse cannot be computed. This section walks you through the theory, the MATLAB commands, practical examples, and common pitfalls you may encounter.
People argue about this. Here's where I land on it.
Why Do We Need the Inverse?
The matrix inverse is a fundamental tool for solving linear systems, performing coordinate transformations, and analyzing system stability. In engineering, physics, economics, and data science you will often see equations of the form
[ \mathbf{A}\mathbf{x}= \mathbf{b}, ]
where x is the unknown vector. If A is invertible, the solution can be written compactly as
[ \mathbf{x}= \mathbf{A}^{-1}\mathbf{b}. ]
Thus, computing the inverse (or, more efficiently, solving the linear system directly) is a routine step in many numerical algorithms.
Basic MATLAB Syntax for the Inverse
| Command | Description |
|---|---|
inv(A) |
Returns the inverse of a square matrix A. |
A^-1 |
Same as inv(A); MATLAB interprets the caret (^) as matrix power. |
pinv(A) |
Returns the Moore‑Penrose pseudo‑inverse (useful for rectangular or singular matrices). |
sym(A) followed by inv(sym(A)) |
Symbolic inverse – gives an exact rational expression when the matrix contains symbolic variables. |
Tip: For most numerical problems you should prefer the backslash operator
\(i.e.,x = A\b) over explicitly forming the inverse. The backslash solves the linear system without ever constructing A⁻¹, which is both faster and more numerically stable The details matter here..
Step‑by‑Step Example: Computing a 3×3 Inverse
% Define a 3x3 matrix
A = [2 1 3;
0 5 1;
4 2 6];
% Check if the matrix is square
if size(A,1) == size(A,2)
% Compute the inverse
Ainv = inv(A);
disp('Inverse of A:');
disp(Ainv);
else
error('Matrix must be square to compute an inverse.');
end
Output
Inverse of A:
0.2500 -0.1250 0.0625
-0.2000 0.3000 -0.1000
0.1000 -0.0500 0.0500
You can verify the result by multiplying the original matrix with its inverse:
I_check = A * Ainv; % should be close to the identity matrix
disp(I_check);
The product will be the identity matrix up to machine precision (e.g.On top of that, , 1. 0000 on the diagonal and values on the order of 1e-15 elsewhere) Not complicated — just consistent..
Detecting Singular or Ill‑Conditioned Matrices
A matrix is singular when its determinant is zero; in that case inv will throw an error:
A_singular = [1 2; 2 4];
inv(A_singular) % MATLAB returns: Error using inv
Even if a matrix is technically invertible, it may be ill‑conditioned, meaning small changes in the input cause large changes in the inverse. The condition number cond(A) quantifies this sensitivity:
condA = cond(A);
if condA > 1e10
warning('Matrix is ill‑conditioned. Consider using pinv or regularization.');
end
When the condition number is huge, the explicit inverse can be unreliable. Also, in such situations the pseudo‑inverse pinv or a regularized solver (e. g., Tikhonov regularization) is preferable.
Using the Pseudo‑Inverse
About the Mo —ore‑Penrose pseudo‑inverse pinv works for any matrix, whether square, rectangular, or singular. For a full‑rank square matrix it returns the same result as inv, but for rank‑deficient matrices it gives the least‑squares solution.
B = [1 2 3; 4 5 6]; % 2x3 matrix
Bplus = pinv(B); % 3x2 pseudo‑inverse
The product B * Bplus approximates the identity on the column space of B, while Bplus * B projects onto the row space But it adds up..
Symbolic Inverses
When you need an exact algebraic expression (for teaching, derivation, or further symbolic manipulation), use the Symbolic Math Toolbox:
syms a b c d
A_sym = [a b; c d];
A_inv_sym = inv(A_sym);
pretty(A_inv_sym)
MATLAB will return the familiar formula
[ \mathbf{A}^{-1}= \frac{1}{ad-bc}\begin{bmatrix} d & -b \ -c & a \end{bmatrix}, ]
provided the determinant (ad-bc\neq0). Symbolic inverses are invaluable for verifying analytical results or for generating code that must work with variable parameters.
Performance Considerations
-
Avoid explicit inverses when solving linear systems.
Instead ofx = inv(A)*b, usex = A\b. The backslash operator exploits matrix structure (e.g., sparsity, symmetry) and is typically several times faster and more accurate. -
Sparse matrices.
If A is sparse, compute its inverse only if you truly need every entry. Often you only need the solution of a linear system, which can be obtained withA\bwhile preserving sparsity. -
Memory usage.
The inverse of an (n\times n) dense matrix requires (n^2) storage locations. For large (n) (e.g., >10 000) forming the full inverse may be impractical; iterative solvers or factorizations (LU, Cholesky) are better choices And it works..
Common Errors and How to Fix Them
| Error Message | Cause | Remedy |
|---|---|---|
| `Matrix is singular to working precision.Consider this: | Check data for linear dependencies, use pinv, or regularize the matrix. Day to day, |
Verify matrix dimensions; use pinv for non‑square matrices. ` |
| `Error using inv.Day to day, | ||
Warning: Matrix is close to singular or badly scaled. But * |
Input is not square. ` | High condition number. |
By following these guidelines,you can obtain reliable inverses, maintain computational efficiency, and avoid the pitfalls associated with ill‑conditioned or ill‑scaled matrices.
Scaling and Pre‑conditioning
When the warning about a nearly singular or badly scaled matrix appears, the first step is to improve the conditioning of the problem.
% Equilibrate the matrix to reduce its condition number
[P, Q, R] = equilibrate(A); % P and Q are permutation/diagonal matrices
A_eq = R * A * C; % C is the column scaling matrix returned by equilibrate
b_eq = R * b; % apply the same row scaling to the right‑hand side
x = A_eq \ b_eq; % solve the scaled system
x = C * x; % back‑transform to the original variables
equilibrate automatically chooses row and column scalings that make the rows and columns of the matrix have comparable norms, often turning a poorly conditioned system into a well‑conditioned one Worth keeping that in mind..
If the matrix is symmetric positive‑definite, the Cholesky factorisation is both faster and more stable than a generic LU decomposition:
R = chol(A); % A = R'*R, where R is upper triangular
x = R \ (R' \ b); % solve using the factorisation
For very large, sparse systems where forming any dense inverse is impossible, iterative solvers such as pcg (preconditioned conjugate gradients) or gmres together with an incomplete factorisation (ichol, ilu) are the tools of choice.
Verifying the Quality of an Inverse
Even when the inversion succeeds, it is good practice to check the result. Two quick diagnostics are:
% Residual norm – how well does A*invA approximate the identity?
invA = inv(A);
residual = norm(A*invA - eye(size(A)), 'fro');
% Condition number – a measure of sensitivity to perturbations
condA = cond(A);
A residual on the order of machine epsilon (eps) and a condition number modestly larger than 1 indicate a reliable inverse. Here's the thing — if cond(A) is huge (e. Because of that, g. , > 1e12), the matrix is numerically singular and any solution derived from its inverse should be treated with caution.
Putting It All Together – A Mini‑Workflow
% 1. Load or construct the matrix A and right‑hand side b
load('myProblem.mat'); % A, b are already in the workspace
% 2. Check conditioning
fprintf('Condition number: %.2e\n', cond(A));
% 3. Attempt a direct solve (no explicit inverse)
x = A \ b;
% 4. If the solve fails or the condition number is alarming,
% equilibrate and retry
if rcond(A) < 1e-12
[P, Q, R, C] = equilibrate(A);
A_eq = R * A * C;
b_eq = R * b;
x_eq = A_eq \ b_eq;
x = C * x_eq;
end
% 5. Verify the solution
fprintf('Residual norm: %.2e\n', norm(A*x - b));
This compact script illustrates the recommended order of operations: try the simplest, most efficient method first; fall back to scaling or factorisations only when necessary; and always validate the result.
Conclusion
In MATLAB, obtaining a matrix inverse is straightforward, but using that inverse wisely is what separates solid numerical code from fragile scripts That alone is useful..
- Prefer the backslash operator or factorisations over explicit
invwhenever you need to solve a linear system. - Reserve
pinvfor rank‑deficient or non‑square problems, and employ symbolic inversion only when an algebraic form is truly required. - Monitor condition numbers and residuals, and apply scaling or pre‑conditioning when the matrix is poorly conditioned.
By following these practices—choosing the right tool, respecting the underlying linear algebra, and verifying results—you will achieve accurate, efficient, and maintainable computations in all of your MATLAB projects.