# Conditional replacement element-wise

I have a $$4\times 4$$ matrix (symbolic). It has a variable, say jj, which should be $$1$$ for diagonal and $$0$$ for non-diagonal entries. I need to write a replacement rule which can do this. Now I am selecting each element and eliminating jj separately using matrix[[1, 1]] /. jj -> 1. But it's too tedious, and I am sure there must be some smarter way to do it.
The original matrix is too large and is very complex. I am writing a sample $$3\times 3$$ matrix over here:

A = {{2 AcD am g1*jj, jj + 1, 3 + g}, {jj + 2*g1, g1*jj,
AcD + jj}, {jj*g1, g1 + jj, AcD+jj*am}}

• In the actual matrix, does jj always enter polynomially (e.g. c1 + c2 jj^2), or can it be inside a more complicated function (e.g. c1 + c2 Log[jj])? Aug 24, 2020 at 10:58
• Yes "jj" always appear as polynomial!
– Rafi
Aug 24, 2020 at 11:37

I would use MapIndexed[] + KroneckerDelta[] for this:

MapIndexed[# /. jj -> Apply[KroneckerDelta, #2] &, A, {2}]
{{2 AcD am g1, 1, 3 + g}, {2 g1, g1, AcD}, {0, g1, AcD + am}}


This works by extracting the Diagonal from the matrix first, setting jj in the diagonal to 1 and adding it again to the matrix, where all jj's have been set to zero:

A = {{2 AcD am g1 jj, jj + 1, 3 + g}, {jj + 2 g1, g1 jj,
AcD + jj}, {jj g1, g1 + jj, AcD + jj*am}}
setDiagonalEntries[m_?MatrixQ] :=
With[{d = Diagonal[m] //. jj -> 1,
o = (m - DiagonalMatrix[Diagonal[m]]) //. jj -> 0},
DiagonalMatrix[d] + o]
setDiagonalEntries[A] // MatrixForm


• Thank you for pointing out the problem with my answer. It would be easy to fix, but since we have the same approach I'll delete my answer. Yours is enough. (You already have my +1.) Aug 24, 2020 at 10:33
• Thanks for your ans..The solution from @infinitezero works for the given example but not with my actual matrix. I modified it a bit and now it works perfectly...Thanks again. That what I did: setDiagonalEntries[m_?MatrixQ] := With[{d = Diagonal[m] //. jj -> 1, o = (m - DiagonalMatrix[Diagonal[m]]) //. jj -> 0}, DiagonalMatrix[d] + o]
– Rafi
Aug 24, 2020 at 11:35
ReplacePart[A, p : Alternatives @@ Position[A, jj] :> Boole[Equal @@ p[[;; 2]]]]

{{2 AcD am g1, 1, 3 + g}, {2 g1, g1, AcD}, {0, g1, AcD + am}}