When I try to calculate a matrix inverse using Matlab\'s inv() operation:
A = rand(10,10);
b = rand(10,1);
C = inv(A);
D = C*b;
I get the foll
You should listen to Matlab and use the second option. inv(A)*b
and A\b
are computed with different algorithms under the hood, and \
is indeed more accurate.
The documentation for inv states:
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 Ax = b. One way to solve this is with 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 mldivide () for further information.
Some additional information:
If you are to calculate
Ax = b
For many different b
's, but with a constant A
, you might want to pre-factorize A
. That is:
[L U P] = lu(A);
x = (U \ (L \ ( P * b)));
Don't know about other fields, but this occurs frequently in power system engineering at least.
If you absolutely need the inverse later on, then you have to compute it. If you can use the backslash operator (\
) instead of an inverse again later on, I would stay away from the inverse and listen to MATLAB's suggestion. For numerical reasons, it is always better to use a slash operator when you can, so the second approach is better even though it is slower.