Mathematica

From AIRWiki
Jump to: navigation, search

Mathematica is a multiplatform product for letting your computer do mathematics for you. It has some benefits with respect to the Matlab numerical environment:

  • it is fully symbolic
  • once learned the language basics, it is usable efficiently
  • it has a cleaner and more consistent namespace for functions
  • it has more powerful simplification capabilities

Unfortunately, its interface is less intuitive and it is less popular at Politecnico wrt Matlab, mostly because Matlab is free to use for DEI (see CIA) and Mathematica is not.

A tutorial

This is a brief tutorial over the most useful operations with Mathematica. It is probably pretty useless trying its content live by issuing its commands on a Mathematica console, step by step. Interestingly, the full, official Mathematica documentation comprises sheets about mathematical concepts that can be cited in scientifical papers.

Basics

When started, Mathematica prompts a blank console. This is actually a Mathematica "document" (or NoteBook) that can include mixes of formulas and text describing them.

Once a formula has been typed in, press Shift-Enter to let Mathematica resolve it (on the Mac the "enter" key also runs the computation). A trivial formula is a symbol or a symbol assignment:

x

or

x = 4

Once a symbol (like "x") has been defined, it is recognized by Mathematica and shown black when typing the next (temporally, not spatially) formulae, not blue. This holds for all recognized symbols: literals, constants and function names.

Vectors and Matrices (Lists)

Matrices are defined with a weird syntax that uses a core concept in Mathematica: lists. (Column) Vectors are:

vec = {1,2,3}

and matrices are simply vectors of vectors (lists of lists):

matr = {{11, 12}, {21, 22}}

This input is sometimes confusing, and the MatrixForm function can help:

MatrixForm[matr]

this presents a list symbol in matrix format.

Functions

Functions have two distinctive features:

  • they always wrap their possible arguments in square brackets
  • their names' words are always capitalized (in Java style)

Everything may be expressed with functions in Mathematica. These are sum and multiplication:

Plus[1,2]
Times[5,4]

and they return 3 and 20, respectively. This is called "full form", that is expressing operation with their full function name. Fortunately, the most common operations have a compact form as well:

1+2
5*4

they evaluate to the same, respectively. When operating with symbols, not numbers, the product is often more handy with the alternate form using just a space between the operands:

5 4

which returns again 20.

Symbolic and numerical evaluation

Mathematica propagates symbolic evaluation until symbols are not associated to a specific value. For example, the cosine function

Cos[x]

returns Cos[x] unless x is defined.

x = 1
Cos[x]

does not return 0.540302 but Cos[4].

The evaluation keeps symbolic not to fall into numerical imprecision propagation, but the actual numerical evaluation can be requested at any time with the N[] function:

N[Cos[x]]

Simplification

Let's introduce a more complicated function:

2 Sin[y] Cos[y]

which is the product (mind the space) between sin(y) and cos(y), multiplied (mind again the space) by 2. We can use Mathematica's smart simplification engine to reduce this expression with the Simplify[]:

Simplify[2 Sin[y] Cos[y]]

that returns Sin[2 y] using prosthaphaeresis formulas.

It is frequently useful to inject some further assumptions to blow the simplification to a further degree. This is pretty easy:

Simplify[Sqrt[a b^2], b > 0]

yields Sqrt[a] b. Assumptions can be composed to any complexity using the && operator.

Defining functions

Custom functions can be defined. Let's say we want to define a custom implementation of the Quaternion algebra that uses lists.

The quaternion conjugate is probably the easiest function: it has arity 1 and inverts the sign of the quaternion's pure part:

QuaternionConjugate = Function[quat, {quat[[1]],-quat[[2]],-quat[[3]],-quat[[4]]}]

This introduces something. The Function[] function is used to define functions. Its result can be assigned to any name, which becomes the function name with which the operation will be called. The syntax is Function[argument or list of multiple arguments, result]. Further, the example shows how to access list elements, with the double square brackets notation. It is assumed that the argument is a valid quaternions as a list of (at least, here) four elements. Otherwise mathematica will generate a type error when the function is executed.

A conceptually better representation of the same function:

QuatConjugate = Function[quat, Flatten[{quat[[1]], -quat[[2 ;; 4]]}]]

this inverts the sign of the whole quaternion's pure part (elements 2 to 4 of q) at once. Since this is a sublist, the Flatten[] is used to avoid a nested list to be returned.

Of course, functions with higher rank can be defined. This is quaternion product:

QuatMultiply = Function[{p, q}, 
 Flatten[{p[[1]]*q[[1]] - p[[2 ;; 4]].q[[2 ;; 4]], 
   p[[1]]*q[[2 ;; 4]] + p[[2 ;; 4]]*q[[1]] + 
    Cross[p[[2 ;; 4]], q[[2 ;; 4]]]}]]

where the argument is now defined as a list of (two) arguments, and some new operations are introduced: the vector dot product "." and the vector cross product Cross[].

Functions can be simplified as well, with the Simplify[] operator. This is one such example:

QuatMultiply = 
 Simplify[Function[{p, q}, 
   Flatten[{p[[1]]*q[[1]] - p[[2 ;; 4]].q[[2 ;; 4]], 
     p[[1]]*q[[2 ;; 4]] + p[[2 ;; 4]]*q[[1]] + 
      Cross[p[[2 ;; 4]], q[[2 ;; 4]]]}]], 
  p \[Element] Reals && q \[Element] Reals && Simplify[Norm[p]] == 1 && 
   Simplify[Norm[q]] == 1]

In this simplification, it is said that both p's and q's components are elements in Real numbers, and that both quaternions have unit norm (see Quaternion). This is necessary because, in the sake of maximum generality, Mathematica always assumes symbols to be Complex. The \[Element] is the <math>\in</math> symbol.

Because Mathematica is fully Unicode, many mathematical symbols can be input along with common ASCII text. For example, the \[Element] symbol can be replaced by the sequence Esc "el" Esc ("el" means the actual characters e and l), the <math>\alpha</math> can be replaced by Esc "alpha" Esc, et cetera.

Tips and Tricks

Notebooks and commented notebooks

It is possible to save a sequence of formulae and their evaluation for latter use. It is thus useful to comment formulae with plain text. Mathematica wraps formulae -- their definition and their computed result -- in blocks. Further blocks can be interleaved between formulae with plain text. Just position between to blocks (where you want to insert text), get the horizontal cursor, then press Control-7 (or use the Format -> Style menu). Text-formatted blocks can contain any kind of formatting: colors, italic etc.

Do comment your notebooks if you have a fair complexity in them.


TeX output

It is very often useful to export Mathematica output to TeX. This is simple with Mathematica:

TeXForm[formula]