Matrix product: inv or \ ?

조회 수: 4 (최근 30일)
Giovanni Gardan
Giovanni Gardan 2020년 5월 20일
댓글: Giovanni Gardan 2020년 5월 20일
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.

채택된 답변

Stephen23
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.
  댓글 수: 1
Giovanni Gardan
Giovanni Gardan 2020년 5월 20일
Thank you very much for your useful answers dear Stephen!
So the \ operator is important even if I'm not resolving a linear system, but I'm simpling doing a product between matrixes?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by