Programming

Index

This index gives a list of keywords that are associated with various cells in this Notebook. If you Command-Double-click one of the keywords below,  Mathematica  will find the cell associated with that keyword, select it, and display it in the center of  your window.

AppendTo  
Block  
Blocks  
Break  
Conditionals  
Conditions  
Continue  
Control`Structures  
Do  
Expression`compound  
FixedPoint  
For  
Functions`control  
Goto  
If  
Incrementing  
Lists`modifying  
Loops    
Module  
Modules  
Nest  
PrependTo  
Programs`sample 
Return  
SameQ  
Switch  
Throw  
TrueQ  
UnsameQ  
Variables`modifying  
Which  
While  
With

A Note on Programming

Mathematica  is a high-level programming language in which you can write programs, both large and small.  The fact that Mathematica  is an interactive system means that you can run your programs as soon as you have typed them in.

Mathematica  programs can make use of the symbolic aspects of Mathematica . They can create and manipulate arbitrary symbolic data structures.  Mathematica  programs themselves are also symbolic expressions, and can be combined and manipulated using standard Mathematica  operations.

Mathematica  supports several programming styles, including:

1) Procedural programming, with block structure, conditionals, 
iteration and recursion.

2) Functional programming, with pure functions, functional operators and program-structure operations.

3) Rule-based programming, with pattern matching and object orientation.

The purpose of this document is to give usage and simple examples of Mathematica  functions and operations. This means that only the most superficial aspects of using Mathematica  as a programming language can be presented.  For more information and examples the user is urged to consult the books  Mathematica : A System for Doing Mathematics by Computer  by Stephen Wolfram and Programming in Mathematica  by Roman Maeder.

Loops and Control Structures

Modifying Variables and Lists

Syntax (see page 248)

i ++  increments the value of i  by 1.

i --  decrements i.

++i   pre-increments i.

--i   pre-decrements i.

i += di   adds di  to the value of i.

i -= di   subtracts di  from i.

x  *= c   multiplies x  by c.

x /= c   divides x  by c.

PrependTo[v, elem ]   prepends elem  to the value of the list v, and resets v  to the result.

AppendTo[v, elem ]   appends elem .

v = {v, elem }   makes a nested list containing elem .

Incrementing

Note that the value of i++ is the value of i  before the increment is done.

i=5; Print[i++]; Print[i]

Pre-Incrementing

Note that the value of ++i is the value of i  after the increment.

i=5; Print[++i]; Print[i]

Specifying the Value of the Increment

t = 7x

t += 18x

t

Updating with Multiplication

This sets t  to 8, multiplies its value by 7, then gives the final value of t .

t = 8; t *= 7; t

Using AppendTo

v = {5, 7, 9}

AppendTo[v, 11]

A Note on AppendTo

Although AppendTo[v, elem ] is always equivalent to                                v  = Append[v, elem ], it is often a convenient notation. However, you should realize that because of the way Mathematica  stores lists, it is usually less efficient to add a sequence of elements to a particular list than to create a nested struucture that consists, for example, of lists of length 2 at each level. When you build up such a structure, you can always reduce it to a single list using Flatten. This is illustrated in the next example.

Nested List Structure

w = {1}; Do[ w = {w, k^2}, {k, 1, 4} ]; w

Flatten[w]

Loops

Syntax (see page 290)

expr1 ; expr2 ;  expr3   evaluates the expri  in turn, returning the result of the last one.

Do[expr, {i, imax }]   evaluates expr  repeatedly, with i  varying from 1 to imax  in steps of 1.

Do[ expr, {i, imin, imax, di }]    evaluates expr  repeatedly with i  varying from imin  to imax  in steps of di.

Do[expr, {n }]    evaluates expr  n   times.

Nest[ f, expr, n ]    applies f   to expr  n   times.

FixedPoint[f, expr ]   starts with expr, and applies f  repeatedly until the result no longer changes.

While[test, body ]    evaluates body  repetitively, so long as test  is True.

For[start, test, incr, body ]    evaluates start , then repetitively evaluates body  and incr, until test  fails.

Using Do

Do[ Print[i^2], {i, 4}]

Specifying the Increment in Do

This executes an assignment for t  in a loop with k  running from 2 to 6 in steps of 2.

t = x; Do[t = 1/ (1 + k t), {k, 2, 6, 2}]; t

Nested Loop

Do[ Print[ {i, j}], {i, 4}, {j, i-1}]

Repeating an Operation

t = x; Do[ t = 1/ (1 + t), {3}]; t

Procedure Inside Do

t = 67; Do[ Print[t]; t = Floor[t/2], {3}]

Using Nest

Nest[ f, x, 3]

Using Nest with a Pure Function

Nest[ Function[ t, 1/ (1 + t)], x, 3]

Using FixedPoint

FixedPoint[
         Function[t, Print[t];Floor[t/2]], 67]

Using While

Note that the parentheses are needed because != has a higher precedence than =.

n = 17; While[ (n = Floor[n/2]) != 0, Print[n]]

Using For

For[i=1, i < 4, i++, Print[i]]

A Note on While and For

The functions While and For in Mathematica  are similar to the  control structures for and while in languages such as C. Notice, however , that there are a number of important differences. For example, the roles of comma and semicolon are reversed in Mathematica  For loops relative to C language ones.

In Mathematica , both While and For always evaluate the loop test before evaluating the body of the loop. As soon as the loop fails to be True, While and For terminate. The body of the loop is thus only evaluated in situations where the loop test is True.

Using For with Compound Expressions

For[i=1; t=x, i^2 < 10, i++, t = t^2 + i;
                          Print[i]]

Control Flow Functions

Break[ ]  exits the nearest enclosing loop.

Continue[ ]  goes to the next step in the current loop.

Return[expr ]  returns the value expr, exiting all procedures and loops in a function.

Goto[name ]  goes to the element Label[name ] in the current procedure.

Throw[expr ]  returns expr  as the value of the nearest enclosing Catch (non-local return).

Using Break

The Break[ ] causes the loop to terminate as soon as t  exceeds 19.

t = 1; Do[t *=k; Print[t];
                 If[t > 19, Break[ ]], {k, 10}]

Using Continue

When k  < 3, the Continue[ ] causes the loop to be continued, without executing  t  += 2.

t = 1; Do[t *= k; Print[t];
      If[ k , 3, Continue[ ]]; t += 2, {k, 10}]

A Note on Control Flow Functions

Control flow functions are recognized only when they are generated directly  as elements of a procedure or values of loop bodies. Mathematica  determines control flow by evaluating expressions, then seeing whether the results are control functions such as Break[ ] and Continue[ ]. It is crucial that control functions appear directly as results of evaluation.  If the results have forms like f  [Break[ ]], they will not be recognized as control flow directives.

Using Return

h[x_] := (If[x > 5, Return[big]];
                     t = x^3; Return[ t - 7])

h[10]

h[4]

Using Catch

g[x_] := If[ x > 10, Throw[overflow], x!]

Catch[ 2 + g[20] ]

Catch[ 2 + g[5] ]

Using Goto

This goes on looping until q  exceeds 6.

(q = 2; Label[begin]; Print[q]; q += 3;
                     If[ q < 6, Goto[begin]])

Conditionals

Syntax (see pages 227 and 286)

lhs  := rhs /; test   uses the definition only if test  evaluates to True.

If[test, then, else ]   evaluates then  if test  is True, and else  if it is False.

If[test, then, else, unknown ]   evaluates unknown  if test  is neither True nor False.

Which[test1, value1, test2, ... ]    evaluates the testi , in turn, giving the value associated with the first one that is True.

Switch[expr, form1, value1, form2, ...]    compares expr  with each of the formi , giving the value associated with the first form it matches.

Switch[expr, form1, value1, form2, ..., _ , def ]    uses def  as a default value.

TrueQ[expr ]    gives True if expr is True, and False otherwise.

lhs  === rhs   or SameQ[lhs, rhs ]   gives True if lhs  and rhs  are identical, and False otherwise.

lhs  =!= rhs   or UnsameQ[lhs, rhs ]   gives True if lhs  and rhs are not identical, and False otherwise.

Using If

If[7 > 8, Print[x], Print[y]]

Function Definition Using If

This defines a step function.

f[x_] := If[x > 0, 1, -1]

Function Definition Using Conditions

This defines the same step function as the previous example.

g[x_] := 1 /; x > 0

g[x_] := -1 /; x <= 0

Function Definition Using Which

Note that using True as the third test makes this the default case.

hw[x_] := Which[x < 0, x^2, x > 5, x^3, True, 0]

hw[-5]

hw[2]

Function Definition Using Switch

r[x_] := Switch[Mod[x, 3], 0, a, 1, b, 2, c]

r[7]

Using Switch with a Default Value

Note that 17 matches neither 0 nor 1, but it does match 
the "blank", _.

Switch[17, 0, a, 1, b, _, z]

Using TrueQ

Because the test yields neither True nor False, the first input is returned unevaluated. However, TrueQ[x  == y ]  gives False because x  == y  is not manifestly True.

If[x == y, a, b]

If[TrueQ[x == y], a, b]

A Note on Conditionals

An important point about symbolic systems is that the conditions you give may yield neither True nor False. Thus for example, the condition x  ==y  does not yield True or False unless x  and y  have specific values, such as numerical ones. However, x  === y  gives False as the two expressions are not manifestly equal. These points are illustrated in the next example.

Using == and ===

Note that the condition x  == y  yields neither True nor False and that the condition x  === y  is False.

If[x == y, a, b, c]

If[x === y, a, b, c]

Blocks and Modules

Syntax (see page 318)

Module[{x, y, ...}, body ]  gives a module with local variables         x , y, ...

Module[{x = x0, y = y0, ...}, body ]   gives a module with initial values for  local variables.

lhs := Module[vars, rhs  /; cond ]   shares local variables between rhs  and cond .

With[{x = x0, y = y0,...}, body ] defines local constants x, y, ...

Block[{x, y, ...}, body ]  evaluates body  using local values for   x , y, ...

Block[{x = x0, y = y0, ...}, body ] assigns initial values to         x , y, ...

Local Variables Using Module

Note that the variable t is local to the module.

t = 17

f[v_] := Module[{t}, t = (1 + v)^2; 
                            t = Expand[t]]

f[a + b]

t

Using a Local Function in a Module

Note that the function f is local to the module.

gfac10[k_] :=
   Module[{f, n}, 
      f[1] = 1; f[n_] := k + n f[n-1]; f[10]]

gfac10[0]

Using Local Variables in Definitions with Conditions

h[x_] := Module[{t}, t^2 -1 /; (t = x - 4) > 1]

h[10]

Specifying Initial Values for Local Variables

g[u_] := Module[{t = u}, t += t/(1 + u)]

g[a]

Initial Values Involving Variables with Global Values

Module[{s = 6, u = s}, u^2]

s = 16

Module[{s = 6, u = s}, u^2]

A Note on Initial Values in Module and With

Note that initial values are always evaluated before the module is executed. As a result, even if a variable x  is defined as local to the module, the global x  will be used if it appears in an expression for an initial value. Just as in Module, the initial values you define in With are evaluated before the With is evaluated.

Local Constants using With

Note that t is a local constant.

t = 17

Clear[w]

w[x_] := With[{t = x + 1}, t + t^3]

w[a]

t

Initial Values in With

Note that the expression t + 1, which gives the value of the local constant t,  is evaluated using the global t.

t = 17

With[{t = t + 1}, t^2]

A Note on Module and With

In some respects, With is like a special case of Module, in which each local variable is assigned a value exactly once. One of the main reasons for using With instead of Module is that it typically makes the Mathematica  programs you write easier to understand. In a module, if you see a local variable x  at a particular point, you potentially have to trace through all of the code in the module to work out the value of x  at that point.  In a With construct, however, you can always find out the value of a local constant simply by looking at the initial list of values, without having to trace through specific code.

Local Values using Block

The Block statement evaluates the previous expression, using a local value for x.  There is no global value for x.

x^2 + 3

Block[{x = a + 1}, %]

x

Local Values and Functions

The function definition depends on the global value of t. Using the Block, you can set up a local value.

t = 17

f[x_] := x^2 + t

f[a]

Block[{t = 2}, f[a]]

A Note on Blocks

In blocks, variables retain their global names, but can have local values. Blocks in Mathematica  effectively allow you to set up "environments" in which you can temporarily change the values of variables. Expressions you evaluate at any point during the execution of a block will use the values currently defined for variables in the block.

Sample Programs

Generating an n  by n  Hilbert Matrix

Here is a simple Mathematica  program which generates an n  by n  Hilbert matrix.

Hilbert[n_] := Table[1/(i + j - 1), {i, n}, {j, n}]

Constructing the Characteristic Polynomial of a Matrix

This program finds the characteristic polynomial for a matrix.
The /; clause at the end checks that m is indeed a matrix.

CharPoly[m_, x_] := 
     Det[m - x IdentityMatrix[Length[m]]] /; MatrixQ[m]

Finding the Next Prime

Here is a procedural program in Mathematica  for finding the next prime after a given integer. The pattern n_Integer matches only integers.

NextPrime[n_Integer] := 
     Module[{k = n}, While[!PrimeQ[k], k++]; Return[k]]

Finding the Mean and Variance of a List of Data

You can often avoid using loops in Mathematica  by operating directly on complete lists. The resulting programs are usually more elegant and more efficient. Here are programs for computing the mean, variance, and quantiles of a list.

Mean[list_List] := Apply[Plus, list] / Length[list]

Variance[list_List] := Mean[ (list - Mean[list])^2 ]

Quantile[list_List, q_] := 
         Part[ Sort[list],
              -Floor[-q Length[list]] ] /; 0 < q < 1

Generating a Random Walk

This function takes a list of random numbers, and forms a succession of cumulative sums, thereby producing a sequence of points in a one-dimensional random walk.

RandomWalk[n_Integer] := 
       FoldList[Plus, 0, Table[Random[ ] - 1/2, {n}]]

Finding a Continued Fraction Approximation

Here is an elegant program, written in a functional programming style, which finds the first n  terms in the continued fraction decomposition of a number x .

ContinuedFraction[x_Real, n_Integer] :=
   Floor[ NestList [ 
           Function[u, 1/(u - Floor[u])], x, n - 1 ] ]

Computing a Jacobian

You can mix symbolic programming constructs with mathematical operations. Outer yields a matrix in which D is applied to all possible pairs of elements from funs and vars.

Jacobian[funs_List, vars_List] := Outer[D, funs, vars]

Defining Rules for Laplace Transforms

It is common to use transformation rules to build up programs in Mathematica. Here are some rules for Laplace transforms.

Laplace[c_, t_, s_] := c/s /; FreeQ[c, t]

Laplace[a_ + b_, t_, s_] := 
                    Laplace[a, t, s] + Laplace[b, t, s]

Laplace[c_ a_, t_, s_] := 
                      c Laplace[a, t, s] /; FreeQ[c, t]

Laplace[t_^n_., t_, s_] := 
               n!/s^(n+1) /; (FreeQ[n, t] && n > 0)

Laplace[a_. Exp[b_. + c_. t_], t_, s_] :=
      Laplace[a Exp[b],  t,  s - c] /; FreeQ[b, c, t]

Producing a Run-Length-Encoded List of Integers

You can write elegant and efficient programs using pattern matching. This rather short program produces a run-length-encoded form of a list of integers.

RunEncode[{rest___Integer, same:(n_Integer)..}] :=
      Append[ RunEncode[{rest}], {n, Length[{same}]} ]

RunEncode[{ } ] :=  {  }

Producing a Polar Plot

Mathematica  programs can create graphics. This program makes polar plots.

PolarPlot[r_, {t_, tmin_, tmax_}] :=
 ParametricPlot[{r Cos[t], r Sin[t]}, {t, tmin, tmax},
                      AspectRatio->Automatic]

Plotting Roots of a Polynomial

Here is a program that plots the solutions to a polynomial equation as points in the complex plane.

RootPlot[poly_, z_] :=
  ListPlot[{Re[z], Im[z]} /. NSolve[poly == 0, z]] /; 
                                PolynomialQ[poly, z]

Reading and Plotting a Matrix

This program makes a three-dimensional plot of a matrix of numbers read from a data file.

FilePlot3D[file_String] :=
           ListPlot3D[ ReadList[
                 file, Number, RecordLists -> True] ]

Searching for a String

You can write programs that manipulate external data. This program gives a list of the files in your current directory that contain a particular string.

Where[s_String] :=
      Select[ FileNames[ ],
                   (Length[FindList[#, s, 1]] > 0)& ]