Mathematica

Defining variables and functions

In the Mathematica examples below, boldface type is Input, regular type is Output.

Pattern matching; general vs. specific definitions


  f[x] = 3x;				(* defines f only for x *)
  { f[a], f[0], f[4], f[4.], f[blah], f[x] }
  {f[a], f[0], f[4], f[4.], f[blah], 3 x}

  f[x_] = 5x;			(* defines f for the general case *)
  { f[a], f[0], f[4], f[4.], f[blah], f[x] }
  {5 a, 0, 20, 20., 5 blah, 3 x}

  f[x_Integer] = "INTEGER!!";		(* defines f for integers *)
  { f[a], f[0], f[4], f[4.], f[blah], f[x] }
  {5 a, "INTEGER!!", "INTEGER!!", 20., 5 blah, 3 x}
Note that specific definitions override the more general definitions, e.g. in the latter output, f(x)=3x as per the first definition, rather than 5x from the (more general) second definition. To remove the (erroneous?) first definition, you would have to Remove[f] and start the definitions over.

Types of expressions include   Integer,   Real,   Rational,   Complex,   Symbol,   List

Immediate vs. delayed evaluation


  Remove[f,g]		(* "undefine" these symbols *)
  a = 5;
  f[x_]  = a x;
  g[x_] := a x;
  { f[x], g[x] }
  {5 x, 5 x}			(the same, so far)

  a = 7;
  { f[x], g[x] }
  {5 x, 7 x}			(g(x) uses current value of a)

Iterative functions; alternatives to "Do" and "For"

If you are used to programming in C or Pascal or Fortran -- ``procedural languages'' -- you may be hooked on using do-loops or for-loops to create or operate on arrays. Mathematica allows you to do things this way, but also provides functional programming commands such as Table, Sum and Product to let you accomplish many of the same tasks in a more ``mathematical'' way.

  Do[ Print[i," squared is ",i^2], {i,1,9,2} ]
1 squared is 1
3 squared is 9
5 squared is 25
7 squared is 49
9 squared is 81

  For[ i=2, i<17, i+=4, Print[i," cubed is ",i^3] ]
2 cubed is 8
6 cubed is 216
10 cubed is 1000
14 cubed is 2744

  Table[ i^2, {i,1,19,3} ]
  {1, 16, 49, 100, 169, 256, 361}

  Sum[ w^i, {i,3,11,2} ]

   3    5    7    9    11
  w  + w  + w  + w  + w

  Product[ (x-n), {n,0,5} ]
  (-5 + x) (-4 + x) (-3 + x) (-2 + x) (-1 + x) x


Map and Apply
Table of Contents