TransWikia.com

Conditional replacement element-wise

Mathematica Asked by Rafi on March 25, 2021

I have a $4times 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 $3times 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}}

3 Answers

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

Correct answer by J. M.'s ennui on March 25, 2021

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

Answered by infinitezero on March 25, 2021

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

Answered by kglr on March 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP