2
$\begingroup$

It seems that Mathematica reserves the capital i, I, for the imaginary unit. I have the following expression:

expr = a.b + II

For the user, I want to display the above expression with just I (for readability, it represents the inertia tensor). So I do:

Print[ToString[ReplaceAll[expr, II -> I] // TraditionalForm]]

But I still get the "imaginary unit" and not an actual capital i:

enter image description here

How do I display a capital i? Thanks! To emphasize: this is just to display to the user in a string output, in the actual code I use II...

$\endgroup$
  • 2
    $\begingroup$ Convert to string first, then use StringReplace? $\endgroup$ – MarcoB Aug 12 '15 at 17:59
  • 2
    $\begingroup$ If you can be sure not to confuse yourself, \[CapitalIota] could be used directly: a.b + \[CapitalIota] $\endgroup$ – chuy Aug 12 '15 at 18:54
6
$\begingroup$

To achieve customized display forms, you use either Format or MakeBoxes. Converting to string is usually a measure of last resort, and not what I would recommend here.

Instead, just do this:

expr = a.b + II

(* ==> II + a.b *)

II /: MakeBoxes[II, StandardForm] := RowBox[{"I"}]

expr = a.b + II

(* ==> I + a.b *)

Edit: TraditionalForm, String output

In MakeBoxes, the second argument can also be a blank pattern to allow the output I not only in StandardForm, as I did above:

II /: MakeBoxes[II, _] := RowBox[{"I"}]

Then, you can for example get this somewhat prettier output:

TraditionalForm[a.b + II]

$a.b+I$

or also this string representation, if desired:

ToString[a.b + II, TraditionalForm]

$\tt a.b+I$

$\endgroup$
4
$\begingroup$
expr = a.b + II;
II2I[n_] := StringReplace[ToString[n], "II" -> "I"];
II2I[expr]
$\endgroup$
3
$\begingroup$

Since you are only doing this for printing then you can simply replace II with "I"

Print[ToString[ReplaceAll[expr, II -> "I"] // TraditionalForm]]
(* a.b + I *)
$\endgroup$

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