Back to Hans Lundmark's main page


Notes on Mathematica

These are my own notes to help me remember things I learn about Mathematica. I'm putting them here just in case someone else happens to be interested.

See Wolfram's Mathematica Documentation Center and The Mathematica Book (v5) for more authoritative information.

A useful overview: Fundamentals of Mathematica Programming by Richard J. Gaylord.

Google search: Mathematica tips.

Some useful questions and answers on Mathematica StackExchange:

Useful stuff

To get all output in FullForm: $Post = FullForm. The command $Post =. resets.

Short[expr] and Short[expr, n] print an abbreviated form of the expression (one line or n lines, respectively).

To prevent evaluation, write Hold[expr] or HoldForm[expr]. (The difference is that the symbol "Hold" is shown in normal output, while "HoldForm" is not.) To stop an argument of a function from being evaluated, wrap it like this: fcn[Unevaluated[expr]].

To remove all user-defined symbols, use Remove["Global`*"]. The command Clear[x] keeps the symbol but removes its values and definitions. The command x=. removes any rules defined for x (what's the difference?).

The syntax for ranges is expr[[start ;; stop]] or expr[[start ;; stop ;; step]].

Importing packages: <<Combinatorica`.

Inputting greek letters and other math symbols: press "ESC a ESC" for alpha, "ESC >= ESC" for ≥, and so on.

Inputting subscripts: press "CTRL-minus".

"CTRL-." enlarges the selection around the cursor.

Expressions

Expressions in Mathematica always have exactly one head (Head[expr] or expr[[0]]) and zero or more elements or parts (expr[[k]]). Both head and elements are themselves expressions. Standard way of writing an expression: head[element1, element2, ...].

Expressions with head only (no elements) are atomic. AtomQ[expr] returns True for such expressions. Atomic expressions contain various built-in magic that non-atomic expressions don't, such as special information that is extracted in other ways than through expr[[k]]. The possible heads for atomic expressions are Symbol, String, Integer, Rational, Real, Complex.

For atomic expressions, Mathematica does not follow the rule of printing an expression as head[element1, element2, ...]. That rule would say that an atomic expression should be printed as just head since there are no elements. But this would be pretty useless and is not done, not even in FullForm. Instead the associated internal information is output: the name string of a symbol (instead of "Symbol"), the value of an integer (instead of "Integer"), etc.

Symbols

An atomic expression with head Symbol contains special information in the form of a string with the name of the symbol, for example "Global`x". The substring up to and including the final "`" is the context of the symbol, and the remainder of the string is the short name. The short name is what Mathematica normally prints (instead of "Symbol"), and what you write in order to access the symbol (unless there are several symbols with the same short name but different contexts, in which case you may have to use the full name to get the one you want).

There are many predefined symbols, like Plus and Sin (whose full names are "System`Plus" and "System`Sin"). If you enter x at the prompt, Mathematica will create a new symbol with the name "Global`x" if it didn't already exist. ($Context shows the current context, which is normally Global` when working at the prompt.) Then Head[x] returns Symbol, SymbolName[x] returns "x", Context[x] returns "Global`", and ?x prints Global`x. The head Symbol that is returned by Head[x] is itself a symbol, that is, an atomic expression with head Symbol (so it is its own head…) and name "System`Symbol".

Expressions input into Mathematica will usually immediately be transformed into a canonical form. Typing x+y+1 gives the response 1 + x + y, while FullForm[x+y+1] shows the internal representation Plus[1, x, y]. If the special rules for printing atomic expressions were not in effect, this would look like Symbol[Integer, Symbol, Symbol], where the first Symbol atom (the head of the expression) contains the string "System`Plus" as (now hidden) internal information, the Integer atom contains the integer value 1, and the remaining two Symbol atoms contain the strings "Global`x" and "Global`y", respectively.

There is yet more magic to the symbol Symbol. If the non-atomic expression Symbol["x"] is input, Mathematica immediately evaluates it to the symbol x, that is, a Symbol atomic expression with the name string "Global`x".

Symbols can carry much more internal information than just the name string; see the section on assignment below, and the documentation for Attributes, Options, OwnValues, DownValues, UpValues, SubValues, DefaultValues, NValues, FormatValues, Messages. The command ??x shows all internal information associated with the symbol x (except that x::usage is the only message shown).

Strings

A string is input using quotation marks "like this", and is an atomic expression with the head String, and internal data consisting of the characters of the string.

Strings are usually printed without quotation marks, which makes it easy to confuse them with symbols. Use InputForm or FullForm to see the quotation marks.

Examples: Typing x+"y"+1 prints 1 + y + x, whereas FullForm[x+"y"+1] prints Plus[1, "y", x], and InputForm[x+"y"+1] prints 1 + "y" + x.

To access individual characters in a string one can't index the string directly (unlike in Python for example), since in Mathematica a string is an atom and thus has no elements. Instead, Characters["string"] gives the list {s, t, r, i, n, g}, where the elements are one-character strings (and not symbols), as can be seen from the FullForm List["s", "t", "r", "i", "n", "g"].

Numbers

The remaining four atoms are numerical types, with a numerical value as internal data. Integer and Real (= floating point numbers) are input as literals, while the other two have constructors with similar magic as Symbol above: the non-atomic expression Rational[3,4] immediately evaluates to an atom with head Rational representing the number 3/4, while Complex[3,4] gives the complex number 3+4i (or 3 + 4 I to Mathematica).

Exception: if you feed the constructors strange data, like Rational[3/4, 5] or Complex[I,2], they remain unevaluated.

Unlike for Symbol, this magic conversion also takes place during output: FullForm[3/4] prints "Rational[3, 4]" and FullForm[3+4I] prints "Complex[3, 4]" (whereas FullForm[x] simply prints "x"). One can tell that something special is going on, since Rational[3,4][[1]] gives the error message "Part specification (3/4)[[1]] is longer than depth of object".

The internal data of a Rational is extracted using Numerator[] and Denominator[], which are always relatively prime integers, with the denominator positive. The real/imaginary parts of a Complex, which can be any other numerical type, are extracted using Re[] and Im[].

NumberQ[expr] tests if an expression is a numerical atom.

NumericQ[expr] tests if an expression is a numerical quantity, according to these recursive rules: it returns True if NumberQ[expr] is true, or if Head[expr] has the attribute NumericFunction and NumericQ[x] is true for all elements x of expr.

Example: NumberQ[Sqrt[3]] is false, but NumericQ[Sqrt[3]] is true, since Attributes[Sqrt] = {Listable, NumericFunction, Protected}.

There are two types of floating point numbers, both with the head Real – machine-precision and arbitrary-precision. Floating point numbers entered as literals are machine-precision numbers, unless suffixed by `nnn which gives a number with nnn digits of precision. Examples: N[Sin[1], 30] prints 0.841470984807896506652502321630, which is the same as Sin[1.0`30]. On the other hand, N[Sin[1.0], 30] gives the same as just Sin[1.0], namely 0.841471, with InputForm 0.8414709848078965 and FullForm 0.8414709848078965`.

Precision[x] gives the number of digits of precision of x (it returns a number – not necessarily an integer! – or one of the symbols MachinePrecision and Infinity).

Binary (or base-b) literal numbers are input as 2^^101 (or b^^n).

IntegerDigits[n] returns a list of the decimal digits in an integer, which can be used to define convenient shorthand notation. For example, if you want to extract submatrices of some matrix A which is smaller than 10×10, defining B[m1_Integer, m2_Integer] := A[[IntegerDigits[m1], IntegerDigits[m2]]] allows you to write B[123,456] instead of A[[{1,2,3},{4,5,6}]]. (This gives the submatrix taken from rows 1, 2, 3 and columns 4, 5, 6.)

Syntactic sugar

There is a lot of special syntax for input and output, but behind the scenes everything is an expression:

x - ySubtract[x, y], which immediately upon input gets transformed to Plus[x, Times[-1, y]]
x / yDivide[x, y], transformed to Times[x, Power[y, -1]]
x ** y ** zNonCommutativeMultiply[x, y, z]
x . y . zDot[x, y, z] (matrix multiplication)
x && y && zAnd[x, y, z]
x || y || zOr[x, y, z]
a <> b <> cStringJoin[a, b, c]
a; b; cCompoundExpression[a, b, c]
{a, b, c}List[a, b, c]
a + b // FPostfix application F[a + b]
F @ a + bPrefix application F[a] + b
a + b ~ F ~ c + dInfix application a + F[b, c] + d
f[[k]]Part[f, k]
    start;;stopSpan[start, stop]
    start;;stop;;stepSpan[start, stop, step]
    ;;stop;;stepSpan[1, stop, step]
    start;; ;;stepSpan[start, All, step]
x = ySet[x, y]
x := ySetDelayed[x, y]
x ^= yUpSet[x, y]
x ^:= yUpSetDelayed[x, y]
f /: x = yTagSet[f, x, y]
f /: x := yTagSetDelayed[f, x, y]
x =.Unset[x]
a -> bRule[a, b]
a :> bRuleDelayed[a, b]
a /. bReplaceAll[a, b]
a //. bReplaceRepeated[a, b]
a @@ bApply[a, b] (replace b's head by a)
a /@ bMap[a, b] (apply a to each element on the first level of b)
a //@ bMapAll[a, b] (apply a to every subexpression of b)
# or #1Slot[1]
## or ##1SlotSequence[1]
f[#1, #2] &Function[f[Slot[1], Slot[2]]]
f'Derivative[1][f]
f''Derivative[2][f]
x == yEqual[x, y]
x === ySameQ[x, y]
x != yUnequal[x, y]
x =!= yUnsameQ[x, y]
x < yLess[x, y]
x <= yLessEqual[x, y]
x > yGreater[x, y]
x >= yGreaterEqual[x, y]
_Blank[]
_hBlank[h]
__BlankSequence[]
___BlankNullSequence[]
x_ or x:_Pattern[x, Blank[]]
x_h or x:_hPattern[x, Blank[h]]
x_.Optional[Pattern[x, Blank[]]]
x_:vOptional[Pattern[x, Blank[]], v]
a | b | cAlternatives[a, b, c]
x /; yCondition[x, y]
x..Repeated[x]
x...RepeatedNull[x]
a?bPatternTest[a, b]

… and a lot more: see here and here.

Assignment

A symbol can be assigned not just one value, but many values of different kinds (numerical values, tranformation rules with pattern matching, attributes, messages, etc.).

A simple assignment like x = y means that from now on, when expressions are evaluated, x will be replaced by whatever value y had at the time of the assignment. A delayed assignment like x := y means that x will be replaced by whatever the expression y evaluates to at the moment when the expression containing x is evaluated. Both these types of assignment are stored in the list OwnValues[x], since they refer to replacement of the symbol x itself.

After y = 3; x = y, the command OwnValues[x] returns {HoldPattern[x] :> 3}.

After y = 3; x := y, the command OwnValues[x] returns {HoldPattern[x] :> y}.

Definitions like x[1] = 5 or x[n_] := n^2 are stored in the list DownValues[x], since they refer to replacing expressions where some particular pattern appears below x. In this example, the list would contain {HoldPattern[x[1]] :> 5, HoldPattern[x[n_]] :> n^2}.

A definition like _[x] ^= 5 is stored in the list UpValues[x], since it refers to replacing expressions where some particular pattern appears one level above x. (However, this particular definition matches the expression UpValues[x], which consequently now will just evaluate to 5 instead of showing us the definition we just made! Although ??x still shows the definition, we'd perhaps better Clear[x] or Remove[x] now …)

See this page for more examples.

Evaluation

To be continued…


Last modified 2015-12-21. Hans Lundmark (hans.lundmark@liu.se)