Matrix product: inv or \ ?
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Giovanni Gardan
il 20 Mag 2020
Commentato: Giovanni Gardan
il 20 Mag 2020
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 Commenti
Risposta accettata
Stephen23
il 20 Mag 2020
Modificato: Stephen23
il 20 Mag 2020
"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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Linear Algebra in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!