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.

  • $\begingroup$ Could you post some sample data for us to try out? It would make experimenting with alternatives easier. $\endgroup$
    – Pillsy
    Commented Oct 14, 2015 at 14:56
  • $\begingroup$ @Pillsy n = 5; m = Partition[Range[n^2], n]; NullSpace[m] $\endgroup$ Commented Oct 14, 2015 at 14:57
  • $\begingroup$ @Pillsy Yes, essentially any square matrix of dimension $d$ whose rank is less than $d$, like in belisarius' example. $\endgroup$
    – instractor
    Commented Oct 14, 2015 at 15:03
  • $\begingroup$ 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... $\endgroup$ Commented Oct 14, 2015 at 15:34
  • 1
    $\begingroup$ @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. $\endgroup$
    – instractor
    Commented Oct 14, 2015 at 17:14

1 Answer 1


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[2];

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]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.