I can do a replacement of an expression with some variables to alternate symbols:

{sx^2, sxy} /. {sx -> Subscript[J, x], 
                sxy ->  Subscript[J, x] Subscript[J, y]}

but if this replacement includes matching square braces, for example instead of $J_x$ above using:

{sx^2, sxy} /. {sx -> [Subscript[J, x]], 
                sxy -> [ Subscript[J, x] Subscript[J, y]]}

then the replacement fails with:

Expression cannot begin with "[Subscript[J, x]]".

I'd like this replacement (only for display purposes) to be $sx \rightarrow [J_x]$, where square brackets is the notation we are using in class for an "ensemble average".

Is there a way to escape the square braces so that the sequence '[', J_x, ']' will be treated as an opaque entity?


A possibility:

MakeBoxes[Subscript[J_, x_], StandardForm] := 
        RowBox[{"[", SubscriptBox[ToString@J, ToString@x], "]"}]

Then evaluating

{sx^2, sxy} /. 
   {sx -> Subscript[J, x], sxy -> Subscript[J, x] Subscript[J, y]}

should return what you want.

enter image description here

Another proposition

One can also directly use MakeBoxes definitions for the variables sx, sy, and so on...

MakeBoxes[sx, StandardForm] := 
        RowBox[{"[", SubscriptBox["J", "x"], "]"}]

This avoids using rules as was done above, but it requires defining MakeBoxes for every variable (though I suppose this process could be automated without much trouble).

|improve this answer|||||
  • $\begingroup$ I figured out after I posted that I could use Row[ "[", ... ] in a replacement expression, but I like your suggestion much better, since it takes the formatting decisions out of the core content. $\endgroup$ – Peeter Joot Nov 25 '15 at 2:53
  • $\begingroup$ Glad you find these propositions useful. Here is yet another possibility: Format[sx] := DisplayForm[RowBox[{"[", SubscriptBox["J", "x"], "]"}]]. $\endgroup$ – user31159 Nov 25 '15 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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