Diagonal Matlab

100 views Asked by At

What is the difference between these two methods to create new matrix just with the diagonal values. The first one ran faster but there is any difference in the accuracy?

d1=diag(1./diag(A));

d2=inv(diag(diag(A)));
2

There are 2 answers

0
Rash On

There are some differences,

A =  [  0     0 ;
      -Inf  -Inf];

d1=diag(1./diag(A))

Inf     0
  0     0

d2=inv(diag(diag(A)))

Inf   Inf
Inf   Inf
0
patrik On

I would say that there is a difference between the methods. I would also assume that the operation that gave d1 were faster without testing it. What is happening then?

d1=diag(1./diag(A));

First you finds the diagonal in A and temporary "store" it in a vector (ans=diag(A)). Then you do a elementwise division on the vector (ans=1./ans). The result for these operations is a vector which length is the min(n,m) where n is the number of rows in A and m is number of columns in A. Then you create a new matrix d1 where the elements in the vector 1./diag(A) are placed in the diagonal (d1=diag(ans)). The rest of the elements are 0.

d2=inv(diag(diag(A)));

First you find the diagonal elements with diag(A). Then you create a diagonal matrix with diag(ans). Thirdly you invert it.

Now what would you think happen in case 2 if one diagonal element is 0? Compare the two cases.