# How to instruct MatrixLog to work with singular matrices?

How to instruct MatrixLog to work with singular matrices by ignoring the zero eigenvalues (thus only acting on a subspace orthogonal to the matrix kernel)?

I'm trying to avoid the arduous journey of getting the eigenvectors (takes a long time) to be able to diagonalize, 'manually' apply the Log function and then go back to the original basis where the matrix is not diagonal.

• Could you post some sample data for us to try out? It would make experimenting with alternatives easier. – Pillsy Oct 14 '15 at 14:56
• @Pillsy n = 5; m = Partition[Range[n^2], n]; NullSpace[m] – Dr. belisarius Oct 14 '15 at 14:57
• @Pillsy Yes, essentially any square matrix of dimension $d$ whose rank is less than $d$, like in belisarius' example. – instractor Oct 14 '15 at 15:03
• MatrixLog[] was never really intended to deal with matrices with eigenvalues lying in the branch cut of the scalar logarithm function. (Conversely, one can never expect MatrixExp[] to return a singular matrix.) I have to wonder exactly what application is having you consider matrix gymnastics of this sort... – J. M.'s torpor Oct 14 '15 at 15:34
• @J.M.In quantum mechanics it is quite common to evaluate the entropy of a quantum state: $-Tr(\rho\log\rho)$. There, you have an $n$-level quantum state $\rho$ but its rank can be less than $n$. In this case $\log(\rho)$ gives nonsense results and to get it right, it is natural to ignore the null space. – instractor Oct 14 '15 at 17:14

## 1 Answer

I use two different definitions in this case. Numerically it seems to suffice to add a fraction of identity. Just make sure the accuracy/stability is good enough for you.

MatrixLogSafe[x_?(MatrixQ[#1, NumericQ] &)] := MatrixLog[x + 1.*^-9 IdentityMatrix[Length[x]]]/Log;


For symbolic expressions I find MatrixFunction convenient:

MatrixLogSafe[x_] := MatrixFunction[Piecewise[{{Log2[#1], #1 > 0}}] &, x];


Note that the definitions are for base 2, but you can easily adjust them if that's the convention in your context.

Edit: By the way, in the application you mention in the comment it seems you don't need the matrix log at all, because you could directly calculate the entropy via

H[x_]:=-Total[Piecewise[{{# Log2[#], # > 0}}] & /@ Eigenvalues[x]]
`