Back to Hans Lundmark's main page
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:
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 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.
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).
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"]
.
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.)
There is a lot of special syntax for input and output, but behind the scenes everything is an expression:
x - y | Subtract[x, y] , which immediately upon input gets transformed to Plus[x, Times[-1, y]] |
x / y | Divide[x, y] , transformed to Times[x, Power[y, -1]] |
x ** y ** z | NonCommutativeMultiply[x, y, z] |
x . y . z | Dot[x, y, z] (matrix multiplication) |
x && y && z | And[x, y, z] |
x || y || z | Or[x, y, z] |
a <> b <> c | StringJoin[a, b, c] |
a; b; c | CompoundExpression[a, b, c] |
{a, b, c} | List[a, b, c] |
a + b // F | Postfix application F[a + b] |
F @ a + b | Prefix application F[a] + b |
a + b ~ F ~ c + d | Infix application a + F[b, c] + d |
f[[k]] | Part[f, k]
|
start;;stop | Span[start, stop]
|
start;;stop;;step | Span[start, stop, step]
|
;;stop;;step | Span[1, stop, step]
|
start;; ;;step | Span[start, All, step]
|
x = y | Set[x, y] |
x := y | SetDelayed[x, y] |
x ^= y | UpSet[x, y] |
x ^:= y | UpSetDelayed[x, y] |
f /: x = y | TagSet[f, x, y] |
f /: x := y | TagSetDelayed[f, x, y] |
x =. | Unset[x] |
a -> b | Rule[a, b] |
a :> b | RuleDelayed[a, b] |
a /. b | ReplaceAll[a, b] |
a //. b | ReplaceRepeated[a, b] |
a @@ b | Apply[a, b] (replace b's head by a) |
a /@ b | Map[a, b] (apply a to each element on the first level of b) |
a //@ b | MapAll[a, b] (apply a to every subexpression of b) |
# or #1 | Slot[1] |
## or ##1 | SlotSequence[1] |
f[#1, #2] & | Function[f[Slot[1], Slot[2]]] |
f' | Derivative[1][f] |
f'' | Derivative[2][f] |
x == y | Equal[x, y] |
x === y | SameQ[x, y] |
x != y | Unequal[x, y] |
x =!= y | UnsameQ[x, y] |
x < y | Less[x, y] |
x <= y | LessEqual[x, y] |
x > y | Greater[x, y] |
x >= y | GreaterEqual[x, y] |
_ | Blank[] |
_h | Blank[h] |
__ | BlankSequence[] |
___ | BlankNullSequence[] |
x_ or x:_ | Pattern[x, Blank[]] |
x_h or x:_h | Pattern[x, Blank[h]] |
x_. | Optional[Pattern[x, Blank[]]] |
x_:v | Optional[Pattern[x, Blank[]], v] |
a | b | c | Alternatives[a, b, c] |
x /; y | Condition[x, y] |
x.. | Repeated[x] |
x... | RepeatedNull[x] |
a?b | PatternTest[a, b] |
… and a lot more: see here and here.
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.
Last modified 2019-11-29. Hans Lundmark (hans.lundmark@liu.se)