MATLAB Functions | Help Desk |
inv
Matrix inverse
Y = inv(X)
Y = inv(X)
returns the inverse of the square matrix X
. A warning message is printed if X
is badly scaled or nearly singular.
In practice, it is seldom necessary to form the explicit inverse of a matrix. A frequent misuse of inv
arises when solving the system of linear equations x
=
inv(A)
*b
. A better way, from both an execution time and numerical accuracy standpoint, is to use the matrix division operator x
=
A\b
. This produces the solution using Gaussian elimination, without forming the inverse. See \
and /
for further information.
Here is an example demonstrating the difference between solving a linear system by inverting the matrix with inv(A)
*b
and solving it directly with A\b
. A matrix A
of order 100 has been constructed so that its condition number, cond(A)
, is 1.e10
, and its norm, norm(A)
, is 1
. The exact solution x
is a random vector of length 100 and the right-hand side is b
=
A
*x
. Thus the system of linear equations is badly conditioned, but consistent.
On a 20 MHz 386SX notebook computer, the statements
tic,
y = inv(A)*b, toc
err = norm(y-x)
res = norm(A*y-b)
produce
elapsed_time = 9.6600 err = 2.4321e-07 res = 1.8500e-09while the statements
tic, z = A\b, toc err = norm(z-x) res = norm(A*z-b)produce
elapsed_time = 3.9500 err = 6.6161e-08 res = 9.1103e-16It takes almost two and one half times as long to compute the solution with
y
=
inv(A)
*b
as with z
=
A\b
. Both produce computed solutions with about the same error, 1.e-7
, reflecting the condition number of the matrix. But the size of the residuals, obtained by plugging the computed solution back into the original equations, differs by several orders of magnitude. The direct solution produces residuals on the order of the machine accuracy, even though the system is badly conditioned.
The behavior of this example is typical. Using A\b
instead of inv(A)
*b
is two to three times as fast and produces residuals on the order of machine accuracy, relative to the magnitude of the data.
The inv
command uses the subroutines ZGEDI
and ZGEFA
from LINPACK. For more information, see the LINPACK Users' Guide.
From inv
, if the matrix is singular,
Matrix is singular to working precision.On machines with IEEE arithmetic, this is only a warning message.
inv
then returns a matrix with each element set to Inf
. On machines without IEEE arithmetic, like the VAX, this is treated as an error.
If the inverse was found, but is not reliable, this message is displayed.
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = xxx
\
Matrix left division (backslash)
/
Matrix right division (slash)
det
Matrix determinant
lu
LU matrix factorization
rref
Reduced row echelon form