Contents

Mathematica tips and tricks

This is a list of Mathematica tips and tricks.

Select vs DeleteCases

DeleteCases and similar functions match patterns, not functions. Select does, so it's often more useful. For instance, to delete cases that match a function, select those which don't. Say you want to remove a sublist from this list (set intersection would do that maybe better, but that's an example):

ltb = Flatten[Table[{m, n}, {m, 0, nmax}, {n, 0, nmax}], 1]
{{0, 0}, {0, 1}, {0, 2}, {0, 3}, {1, 0}, {1, 1}, {1, 2}, {1, 3}, {2, 
  0}, {2, 1}, {2, 2}, {2, 3}, {3, 0}, {3, 1}, {3, 2}, {3, 3}}
Select[ltb, Not[MemberQ[{{0, 0}, {0, 1}, {1, 0}}, #]] &]
{{0, 2}, {0, 3}, {1, 1}, {1, 2}, {1, 3}, {2, 0}, {2, 1}, {2, 2}, {2, 
  3}, {3, 0}, {3, 1}, {3, 2}, {3, 3}}

Position

Often you want something like this:

Position[mylist,#!=0&]

which is not syntactically correct in Mathematica (this syntax works in Select[] for instance, but not in Cases[], to me it's a bit inconsistent).

The following almost works:

Position[mylist,Expect[0]]

but it finds the head of your list and apparently other things as well, so you get results like {0}.

It's better to process mylist directly:

Position[#!=0&/@mylist,True]

Progress bar

Use before any (long) loop over $i$:

ProgressIndicator[Dynamic[i], {imin, imax}]

I don't know why it's called "ProgressIndicator" and not "ProgressBar".

You can also use the more informative Monitor[].

Plot labels

This can be used to set aligned axis labels, without framing the plot (just add popts in the Plotting[] command):

popts = {
  FrameLabel -> {
    {"x axis title", None},
    {"y axis title", None}},
  Frame -> {{True, False}, {True, False}}}

$\mathrm{\LaTeX}$

To export from $\mathrm{\LaTeX}$ [1] (typesetting through the notebook can be unreliable as it can revert a full expression to pseudocode):

ToExpression["string", TeXForm, HoldForm]

e.g.,

ToExpression[" a^\\dagger aa^\\dagger a a^{\\dagger k}a^l", TeXForm, \
HoldForm]

returns

Screenshot 20230613 181900.png

Note that the \ should be escaped (so doubled). That will work without doing it but generates a warning.