Matrix product: inv or \ ?
2 次查看(过去 30 天)
显示 更早的评论
I have four input matrixes and I'd like to do the simple following operation:
(Ygg - Ygl*inv(Ytotll)*Ylg)
where:
Ygg is 3x3 matrix
Ygl is 3x1000 matrix
Ylg is 1000x3 matrix
Yll is 1000x1000 matrix
- I noticed that the first two ways to do the operation are always faster and the third is the slower one. Why using \ is faster than inv? Is there a numerical reasone?
- Sometimes the first is faster than the second and sometimes the second is faster than the first. Is there any numerical-theoretical reasone about this behaviour?
Ygg = rand(3,3);
Ygl = rand(3,1000);
Ylg = rand(1000,3);
Yll = rand(1000,1000);
%Three different way to calculate the same product
tic;(Ygg - Ygl*(Yll\Ylg));toc
tic;(Ygg - (Ygl/Yll)*Ylg);toc
tic;(Ygg - Ygl*inv(Yll)*Ylg);toc
----------------------------------------------------------------------------------------
first run
Elapsed time is 0.022906 seconds.
Elapsed time is 0.023616 seconds.
Elapsed time is 0.059908 seconds.
second run
Elapsed time is 0.031426 seconds.
Elapsed time is 0.028280 seconds.
Elapsed time is 0.057623 seconds
third run
Elapsed time is 0.025449 seconds.
Elapsed time is 0.028944 seconds.
Elapsed time is 0.068196 seconds.
0 个评论
采纳的回答
Stephen23
2020-5-20
编辑:Stephen23
2020-5-20
"Why using \ is faster than inv? Is there a numerical reasone?"
Yes: because the two division operators use completely different, faster, more stable algorithms than inv:
This is explained in the inv documentation: "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 the equation is with x = inv(A)*b. A better way, from the standpoint of both execution time and numerical accuracy, is to use the matrix backslash operator x = A\b. This produces the solution using Gaussian elimination, without explicitly forming the inverse. See mldivide for further information."
"Is there any numerical-theoretical reasone about this behaviour?"
I doubt that there is any real significance between the two division operations, they will both resolve down to the same elimination algorithms. The time differences you see are not significant, and are likely due to random other tasks being performed by your OS.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Linear Algebra 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!