5
$\begingroup$

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}}
$\endgroup$
2
  • $\begingroup$ 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])? $\endgroup$ Aug 24, 2020 at 10:58
  • $\begingroup$ Yes "jj" always appear as polynomial! $\endgroup$
    – Rafi
    Aug 24, 2020 at 11:37

3 Answers 3

6
$\begingroup$

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}}
$\endgroup$
4
$\begingroup$

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

enter image description here

$\endgroup$
2
  • 2
    $\begingroup$ 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.) $\endgroup$
    – C. E.
    Aug 24, 2020 at 10:33
  • $\begingroup$ 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] $\endgroup$
    – Rafi
    Aug 24, 2020 at 11:35
0
$\begingroup$
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}}
$\endgroup$

Your Answer

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

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