Canonical way to map a function to diagonal elements of a square matrix?

Using b.gates.you.know.what's idea:

With[{f = Log}, 
     MapIndexed[Function[{x, id}, If[Equal @@ id, f[x], x]], A, {2}]]

Using an undocumented function:

res = A;
With[{f = Log}, LinearAlgebra`Private`SetMatrixDiagonal[res, f[Diagonal[res]]]];
res

Note that this function modifies matrices given to it, so you'll need to make a copy if you still need the starting matrix.


A modification of a method given by Leonid Shifrin in Mathematica programming: an advanced introduction

A// MapThread[ReplacePart, {#, Log@Diagonal[#], Range[Length@#]}]&

{{1, 0}, {0, 1}}

There is a discussion in this old SO question: Changing the Diagonals of a Matrix with Mathematica


I don't know if there are 10 different ways, but here's a third.

Start with A and subtract off the diagonal, modify the diagonal with your function (Log) and add it back in:

A - DiagonalMatrix[Diagonal[A]] + DiagonalMatrix[Log[Diagonal[A]]]