Code Analyzer: INV is slow and inaccurate

为君一笑 提交于 2019-12-02 13:31:55

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/16545375/code-analyzer-inv-is-slow-and-inaccurate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!