Frage

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 following warning at the last row: INV is slow and inaccurate. Use A\b for INV(A)*b , and b/A for b*INV(A).

I can change the code above into:

A = rand(10,10);
b = rand(10,1);

C = inv(A);
D = A\b;

Now I don't get the warning, but I don't think this solution is better.

Note: I need to store both the inverse of matrix A as well as inv(A)*c. Also, in my real file the size of matrix A can be 5000 x 5000 or even bigger.

Are there any better solutions in terms of efficiency and accuracy or is the first method fine?

War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top