Basic Mathematica

Revised 2008-Jan-31

Full documentation is available from The Mathematica website. There are tutorials etc at the Learning Center.

Please tell the Professor if you have suggestions for improvements to this documentation.

  1. Running mathematica
    Under Unix-based operating systems, type math to get the "programmers" interface, mathematica to get the Notebook interface. Each command you type yields a result. If you finish the command with a semicolon then the result will not be printed. (NB: In the notebook, you have to type Shift+Return to finish an expression.) Much of the notation will be familiar if you know how to program in C.
  2. Expressions.
    The usual operators work as expected:
    x = 2*(3+4/2)
      10
    x^2
      100
    y = 2 (3+4/2)   (* you can leave out the "*" operator *)
      10
    
    Mathematica treats numbers without decimal points as exact, and does not numerically evaluate them. To force numerical evaluation, use the N function, or put a decimal point in a number somewhere:
    x = 70/10
      7
    x = 70/9    (* No decimal point, so not evaluated *)
      70/9
    x = 70.0/9
      7.77778
    x = N[70/9]
      7.77778
    
    Exponential notation is done by the "*^" sumbol,
    3.5*^15;
    3.5 * 10^15; (* same thing *)
    
    To print numbers and text, just use Print. The SetPrecision function controls the number of digits printed.
    Print["The log of ",3.5*^15," is ",Log[3.5*^15] ];
                     15
    The log of 3.5 10   is 35.7915
    
    Print["The log of ",3.5*^15," is ",SetPrecision[Log[3.5*^15],8] ];
                     15
    The log of 3.5 10   is 35.791539
    
    If you don't like the way exponentials are printed, use the "CForm" function to get the more standard "e" notation:
    Print[CForm[3.5*^15]];
      3.5e15
    
  3. Built-in mathematical functions
    These are as you would expect, but they always start with a capital letter, and use square brackets:
    Sqrt[2]*Cos[2*Pi]
      1.4142
    ArcTan[4]
      ArcTan[4]  (* No decimal points, so not evaluated! *)
    ArcTan[4.0]
      1.32582    (* all trig functions are in radians *)
    5!       (* factorial *)
      120
    Gamma[6] (* gamma function *)
      120
    
    Note that π is given by Pi, and e by E.
  4. User-defined functions
    phi[x_] := 1/(1+x^2);
    psi[x_,a_] := 1/(1+(x/a)^2);
    
    You can use letters, numbers, and the dollar symbol in function/variable names. Here is a more complicated function, with local variables:
    bump$fn[x_,a_] := Module[{l1,l2},
     l1 = x/a;  
     l2 = 1/(1+l1^2);
     Return[l2];
    ];
    
  5. Plotting

    One function:
    Plot[ Cos[x], {x,-Pi,Pi} ];
    
    The plot is itself a "Graphics" object that can be stored in a variable:
    plot1 = Plot[ Cosh[x], {x,-Pi,Pi} ];
    
    Plotting multiple functions:
    Plot[ {Sin[x],Cos[x]}, {x,-Pi,Pi} ];
    
    To specify the y-limits of the plot as well as the x-limits:
    Plot[ Cos[x], {x,-Pi,Pi}, PlotRange->{-0.5,0.5}];
    
    To write the plot to an encapsulated PostScript file, create it as a Graphics object and then "Export" it:
    Export["file.eps",plot1];
    
    Mathematica infers the format from the dot-extension of the filename. Other possibilities include png, pdf, svg, etc.
  6. Numerical Integration

    NIntegrate[ 1-x^2,{x,0,1}]
      0.666667
    
    or, using a previously-defined function,
    NIntegrate[ phi[x],{x,0,Infinity}]
      1.5708
    NIntegrate[ psi[x,1.0],{x,0,1}]
      0.785398
    
  7. Complex numbers

    The square root of -1 is written is written as I.
    Exp[I*3.0]
      -0.989992 + 0.14112 I
    
    You can obtain real and imaginary parts of any expression using the Re and Im functions. Functions can accept complex arguments, so you can write things like
    NIntegrate[ Exp[3*I*x] * Exp[-(x-1)^2],{x,-Infinity,Infinity}]
      -0.184946 + 0.0263634 I
    
    Complex conjugate is the Conjugate function:
    Conjugate[ 3 + 4 I ]
      3 - 4 I
    
    You can plot the real and/or imaginary parts of a complex function:
    f[x_] := Exp[(-2+3*I)*x];
    Plot[ Re[f[x]], {x,0,2}];
    Plot[ {Re[f[x]],Im[f[x]]}, {x,0,2}];
    
  8. Arrays and Matrices
    A 1D array is a list
    v = {2.0, -1.0, 0.0} ;
    
    A matrix or 2D array is a list of lists:
    M = {
     {1.3, -2.0, 0.9},
     {-2.2, 0.3, 1.1},
     {-1.4, 1.5, -0.2}
    };
    
    Matrix multiplication or dot product uses the dot operator. Scalar multiplication uses "*",
    w = 0.5 * M.v
      {2.3, -2.35, -2.15}
    w.v
      6.95
    
    There are many useful built-in matrix functions:
    Minv = Inverse[M];
    MT = Transpose[M];
    
    evals = Eigenvalues[M]
      {2.91742, -1.69075, 0.173336}
    evecs = Eigenvectors[M]
      {{-0.512376, 0.661041, 0.548175}, 
       {-0.587781, -0.775991, 0.228806}, 
       {0.397766, 0.553388, 0.731809}}
    
    Norm[v]   (* sqrt of sum of absolute value squared of elements *)
      2.23607
    Norm[M]
      3.59095  
    
    User defined functions of matrices are just like any other function. Here are some useful ones:
    Commutator[a_,b_]    := a.b - b.a;
    Anticommutator[a_,b_]:= a.b + b.a;
    Adjoint[m_] := Transpose[Conjugate[m]];
    
    Subscripting uses double square brackets. Subscripts start at 1. This is one of the differences between Mathematica and C or Python. (The "zeroth" element of a list is its type, actually).
    v[[3]]
      0.
    M[[2,3]]   (* treat M like a matrix *)
      1.1
    M[[2]][[3]] (* treat M like a list of lists *)
      1.1
    
    Printing matrices in a more readable form:
    Print[MatrixForm[M]];
    
  9. Sum and product
    s = Sum[ 1.0/n, {n,1,100}]
      5.18738
    s = Sum[ 1.0/n^2, {n,1,Infinity}]
      1.64493
    p = Product[ (1+1.0/n),{n,1,10}]
      11.0
    
  10. Programming
    To read in and run a file containing mathematica commands:
    << mydefinitions.m
    
    Flow-of-control: "for" loop, and "if" test:
    For[mu=1,mu<=4,mu++,  (* mu++ means mu=mu+1, same as mu+=1 *)
     For[nu=1,nu<=4,nu++,
      If[mu==nu,
       Print[mu,"  ",nu,"   equal!"]
      , (* else *)
       Print[mu,"  ",nu]
      ]
     ]
    ];
    
    Flow-of-control: "while" loop:
    n=0; sum=0; x=1.5;
    While[n<10,
     n = n+1;
     sum = sum + x^n/(n!);
    ];