Mathematical and Statistical Application - Mathematica - Tutorial


What is Mathematica?

According to Wolfram Research, the vendor of this software, Mathematica is the world's only fully integrated environment for technical computing. It handles a wide variety of numerical, algebraic, graphical, and other tasks, which previously could be done only by using many separate software packages. It can be used as everything from a simple calculator to a high-level programming language.

But enough of the marketing jargon... In simple terms, Mathematica is just a really versatile math software package.

For more information on Mathematica, please visit [ http://www.wolfram.com ] Wolfram Research.

The Mathematica Windows

The window in which you type is called a notebook , part of the Mathematica front end which handles interaction with the user; the Mathematica kernel actually performs the calculations.

Most Mathematica input must be entered as text, but the palettes in the palette window can be used for some common functions and constants.

To execute input, press shift-return. To interrupt the execution of input, go to Kernel -> Quit Kernel . This is located on the Mathematica bar in the Microsoft Windows version of Mathematica, or the Notebook window in the UNIX versions of Mathematica. ALT-, will also halt execution.

When Mathematica executes input, it adds the label In[n]:= and gives the output. For example, when you type 1+2, Mathematica gives:

In[1]:= 1+2
Out[1]:= 3

If Mathematica finds an error in your input, it will produce a warning message. Each message has a name, and you can switch off particular error messages using

Off[Function::tag]

If you don't want to see them. To turn messages back on, use

On[Function::tag]

For example, if you enter Sqrt[4,5], Mathematica responds:

In[1]:= Sqrt[4,5]

   Sqrt::argx:
Sqrt called with 2 arguments; 1 argument is expected.

Out[1]:= Sqrt[4,5]

Typing Off[Sqrt::argx] followed by Sqrt[4,5] produces:

In[2]:= Off[Sqrt::argx]

In[3]:= Sqrt[4,5]

Out[3]:= Sqrt[4,5]

Type On[Sqrt::argx] to turn the warning message back on.

Descriptions of all warning messages can be found in the Mathematica Help. Help -> Help Browser in the Windows command bar when using Mathematica for Microsoft Windows, and “ Help Browser ” on the UNIX startup palette contain extensive help on all Mathematica input commands. Additionally, the [ http://reference.wolfram.com/mathematica/guide/Mathematica.html ] Mathematica manual is located online.

Numerical Calculation Notes

  • The arguments of all Mathematica functions are enclosed in square brackets.

  • The names of all built-in Mathematica functions and symbols begin with capital letters.

  • Arithmetic is the same as on a regular calculator. Note that multiplication can be represented by a space, *, or parentheses, and a power is represented by ^. The following is the Mathematica output from simple examples

    In[1]:= 2 3
    
    Out[1]:= 6
    
    In[2]:= 2 * 3
    
    Out[2]:= 6
    
    In[3]:= 2(3)
    
    Out[3]:= 6
    
    In[4]:= 2^3
    
    Out[4]:= 8

  • Scientific notation is entered, for example, as 3.1*^5 or 3.1 10^5

  • By default, Mathematica produces exact results. To get an approximate numerical value, use expr //N . Also, when using a decimal point, Mathematica assumes the number is accurate only to a fixed number of decimal places. By placing a decimal after an integer, you can force Mathematica to give you approximate results. To specify a particular number of significant digits, say n, use N[expr,n] . Note, however, that unless the numbers in expr are exact or of sufficiently high precision, N[expr,n] may not be able to give results with n-digit precision. For example:

    In[1] := 1 + 1/3
    
    Out[1]:= 4/3
    
    In[2]:= Sqrt[2]
    
    Out[1] := document image - no alt tag available. sorry
    
    In[3]:= 1. + 1/3
    
    Out[3]:= 1.33333
    
    In[4]:= Sqrt[2.]
    
    Out[4]:= 1.41421
    
    In[5]:= 1 + 1/3 //N
    
    Out[5]:= 1.33333
    
    In[6]:= Sqrt[2] //N
    
    Out[6] := 1.41421
    
    In[7]:= N[E, 20]
    
    Out[7]:= 2.7182818284590452354

  • Some useful mathematical functions and constants:

    square root of x Sqrt[x]
    exponential Exp[x]
    natural logarithm of x Log[x]
    base b logarithm of x Log[b,x]
    trigonometric functions (arguments in radians) Sin[x], Cos[x], Tan[x]
    absolute value of x Abs[x]
    closest integer to x Round[x]
    pseudo random number between 0 and 1 Random[ ]
    maximum and minimum of x, y, ... Max[x,y, ...], Min[x,y, ...]
    prime factors of n FactorInteger[n]
    integer part of x IntergerPart[x]
    fractional part of x FractionalPart[x]
    k modulo n (remainder from dividing k by n) Mod[k, n]
    factorial n(n-1)(n-2)....1: n!
    binomial coefficient, document image - no alt tag available. sorry = document image - no alt tag available. sorry Binomial[n,m]
    Euler gamma function, document image - no alt tag available. sorry Gamma[z]
    i = document image - no alt tag available. sorry I
    document image - no alt tag available. sorry Infinity
    document image - no alt tag available. sorry Pi
    document image - no alt tag available. sorry E
    document image - no alt tag available. sorry : degrees to radians conversion factor Degree

  • You can get descriptions of all functions directly from the Mathematica kernel by typing ?<Function> , where <Function> is the name of a function. For example:

    In[8]:= ?Sqrt
       Sqrt[z] gives the square root of z

  • Mathematica contains an extensive list of packages of extra functions that can be loaded. Descriptions of these can be found in the Help Browser from the Add-ons & Links tab under Standard Packages. You can also find the help documentations following this [ http://www.wolfram.com/products/fields/ ] webpage. To load an add-on package, type name where name is the name of the package. For example the program listing

    In[1]:= <<Miscellaneous`ChemicalElements`
    
    In[2]:= AtomicWeight[Tungsten]
    
    Out[2]:= 183.84

    illustrates the breadth of Mathematica. This add-on provides abbreviations, atomic weights, and atomic numbers of the elements in the periodic table!

Building Up Calculations

  • To refer to a previous result, Mathematica uses %. Use %% for the next-to-last result, and %%...% (k times) for the kth previous result. For example,

    In[1]:= 5+5
    
    Out[1]:= 10
    
    In[2]:= %+7
    
    Out[2]:= 17
    
    In[3]:=  % + %%
    
    Out[3]:= 27

  • Variable naming conventions

    • If you define a variable as having a specific value, say x=7, it retains that value throughout your entire session. Problems could arise if you forget this. Thus, it is generally a good idea to remove values of a variable after you use them. To do this, use x = . or Clear[x].

    • Mathematica differentiates between upper- and lower-case letters. Hence, for example, the variable X is different from the variable x. Predefined Mathematica variables always start with capital letter, so to avoid duplicating these, it is generally a good idea to name your own variables with lower-case letters.

    • Variable names can be of any length but cannot start with a number. For example, x5 could be a variable, but 5x is not an allowed variable name but is interpreted as 5 times x by Mathematica

    • To define a list of objects, use curly brackets as in the example:

      In[1]:= {1,2,3,4,5}
      
      Out[1]:= {1,2,3,4,5}

      You can then perform functions on the whole list at once instead of having to repeat the calculation multiple times as demonstrated by the code:

      In[1]:= a={1,2,3,4,5}
      
      Out[1]:= {1,2,3,4,5}
      
      In[2]:= a*4
      
      Out[2]:= {4,8,12,16,20}

      To extract a particular value of a list, use Part[list,i] or list[[i]]. For example:

      In[3]:= Part[a,2]
      
      Out[3]:= 2
      
      In[4]:=Part[{1,2,3,4,5},2]
      
      Out[4]:= 2
      
      In[5]:= a[[2]]
      
      Out[5]:= 2
      
      In[6]:= {1,2,3,4,5}[[2]]
      
      Out[6]:= 2

      Likewise, to extract a list of elements from a list, use Part[list, {i,j,...}] or list[[{i,j,...}]]. Mathematica contains an extensive collection of additional functions pertaining to working with lists; these can be found in the Mathematica Help.

  • To perform repetitive operations in another way, use the Do function, which works like an iterative do loop in many programming languages. The right side of the table below gives the Mathematica commands to perform the operations described on the left side.

    Evaluate expr with i running from 1 to imax Do[expr, {i, imax}]
    Evaluate expr with i running from imin to imax in steps of di Do[expr, {i, imin, imax, di}]
    Print expr Print[expr]
    Make a list of the values of expr with i running from 1 to imax Table[expr, {i, imax}]

  • So far, we've used four types of bracketing: parentheses used for grouping, (whatever), square brackets used for functions, f[x], curly brackets used for lists, {a,b,c}, and double square brackets used for indexing, a[[i]].

  • When doing calculations, often you'll go through multiple steps. You can do each step on a separate line or combine them into one using semicolons. Mathematica won't print output from any command with a semi-colon after it. For example,

    In[1]:= a={1,2,3,4,5}; b=2*a; b[[3]]
    
    Out[1]:= 6

Algebraic Calculations

  • Mathematica can do symbolic computations using the same operators as in numerical calculations. For example:

    In[1]:= 3 x^2 + 9 x - 5 x^2
    
    Out[1]:= 9 x - 2 x^2
    

  • The function Expand multiplies out products and powers. The function Factor does the reverse and factors a long expression. The function Simplify attempts to find the simplest form of an expression by using standard algebraic transformations. The function FullSimplify tries to find the simplest form of an expression by using a larger range of algebraic transformations than included in the Simplify function.

    In[1]:= Expand[(x + y) (x + y) (x + y)]
    
    Out[1]:= x3 + 3 x2 y + 3 x y2 + y3
    
    In[2]:= Factor[%]
    
    Out[2]:= (x + y)^3
    
    In[3]:= Simplify[1/(4 (-1+x)) - 1/(4 (1+x)) - 1/(2 (1+x^2))]
    Out[3]:= document image - no alt tag available. sorry
                   

  • Some more useful algebraic functions:

    ExpandAll[expr] Apply Expand everywhere (not just to products and powers)
    Together[expr] Put all terms over a common denominator
    Apart[expr] Separate into terms with separate denominators
    Cancel[expr] Cancel common factors between numerators and denominators
    Collect[expr,x] Group together powers of x
    FactorTerms[expr,x] Pull out factors that do not depend on x
    TrigExpand[expr] Expand trig expressions into a sum of terms
    TrigFactor[expr] Factor trig expressions into products of terms
    TrigToExp[expr] convert trig functions to exponentials
    ExptoTrig[expr] Convert exponentials to trig functions
    Coefficient[expr, form] Coefficient of form in expr
    Exponent[expr, form] Maximum power of form in expr
    Part[expr, n] or expr[[n]] nth term of expr
    Numerator[expr] Numerator of expr
    Denominator[expr] Denominator of expr
    Short[expr, n] Show an n-line outline of expr (used for particularly long expressions)

Calculus

  • Mathematica does a variety of the plethora of calculations we know and love as calculus. Some useful calculus functions: (note that many of these can be entered using the palettes in the palette window.)

    D[f,x] The partial derivative, document image - no alt tag available. sorry
    D[f, x1, x2, ...] Multiple derivative document image - no alt tag available. sorry
    Integrate[f, x] The indefinite integral document image - no alt tag available. sorry
    Integrate[f, x, y, ...] The multiple integral document image - no alt tag available. sorry
    Integrate[f, {x, xmin, xmax}] The definite integral document image - no alt tag available. sorry
    Integrate[f, {x, xmin, xmax}, {y, ymin, ymax}, ...] The multiple integral document image - no alt tag available. sorry
    Sum[f, {i, imin, imax}] The sum document image - no alt tag available. sorry
    Sum[f, {i, imin, imax, di}] The sum with i increasing in steps of di
    Sum[f, {i, imin, imax}, {j, jmin, jmax}] The nested sum document image - no alt tag available. sorry
    Product[f, {i, imin, imax}] The product document image - no alt tag available. sorry
    Solve[lhs==rhs, x] Solution to an equation for x
    Solve[{lhs1==rhs1, lhs2==rhs2, ...}, {x, y, ...}] Solve a set of simultaneous equations for x, y, ...
    Series[f, {x, x0, order}] A power series expansion of f about the point x = x0
    Limit[f, x -&gt; x0] The limit limx->x0f
    Eliminate[{lhs1==rhs1, lhs2==rhs2, ...}, {x, ...}] Eliminate x, ... in a set of simultaneous equations
    Reduce[{lhs1==rhs1, lhs2==rhs2, ...}, {x, y, ...}] Give a set of simplified equations, including all possible solutions
    Normal[series] Truncate a power series to give an ordinary expression

Statistics

  • Mathematica contains the following add-on statistical packages. Refer to the Mathematica Help for detailed information about these. These packages are nice if you want to know something about a common distribution such as the normal or binomial distribution (especially expected values), but fall far behind programs like SAS or Stata for data manipulation functions and any functions requiring advanced statistical theory.

    Statistics`ConfidenceIntervals` Confidence intervals for data which are univariate normal
    Statistics`ContinuousDistributions` Properties of common continuous statistical distributions
    Statistics`DataManipulation` Utilities for data manipulation
    Statistics`DataSmoothing` smoothing of data
    Statistics`DescriptiveStatistics` Common descriptive statistics for data
    Statistics`DiscreteDistributions` Properties of common discrete statistical distributions
    Statistics`HypothesisTests` Hypothesis tests based on the normal distribution (for small sample sizes)
    Statistics`LinearRegression` Linear regression analysis using the method of least-squares
    Statistics`MultiDescriptiveStatistics` Common descriptive statistics for multivariate data
    Statistics`MultiDiscreteDistributions` Properties of the multinomial, negative multinomial, and multiple Poisson distributions
    Statistics`MultinormalDistribution` Properties of the multinormal, multivariate Student-t, Wishart, Hotelling T2, and quadratic form distributions
    Statistics`NonlinearFit` Nonlinear fitting of data
    Statistics`NormalDistribution` Subset of Statistics`ContinuousDistributions` containing properties of only the normal, Student-t, chi-square, and F-ratio distributions

Matrices

  • Matrices in Mathematica are entered as lists of lists. For example, entering {{a,b},{c,d}} results in the matrix document image - no alt tag available. sorry Matrix multiplication is represented by ., and matrix division is, of course, not defined. * represents scalar or element wise multiplication and + and - operators represent matrix addition and subtraction.

  • Some useful functions for matrices are:

    Table[f, {i, m}, {j, n}] Build an m by n matrix by evaluating the function f with i ranging from 1 to m and j ranging from 1 to n
    IdentityMatrix[n] generate an n by n identity matrix
    DiagonalMatrix[list] generate a square matrix with the elements in list on the diagonal
    list[[i]] or Part[list, i] Returns the ith row in the matrix list
    list[[i,j]] or Part[list, i, j] Returns the i,j th element in the matrix list
    Dimensions[list] Returns the dimensions of a matrix represented by list
    MatrixForm[list] Display list in matrix form
    MatrixPower[list, n] nth power of a matrix
    Inverse[list] matrix inverse
    Det[list] determinant
    Transpose[list] transpose
    Tr[list] trace
    Eigenvalues[list] eigenvalues
    Eigenvectors[list] eigenvectors

Graphics

  • Some useful graphics functions:

    Plot[f, {x, xmin, xmax}] Plot f as a function of x from xmin to xmax
    Plot[{f1, f2, ...}, {x, xmin, xmax} Plot several functions together
    ListPlot[{{x1, y1}, {x2, y2}, ...}] Plots several data points
    ContourPlot[f, {x, xmin, xmax}, {y, ymin, ymax} Make a contour plot of f as a function of x and y
    DensityPlot[f, {x, xmin, xmax}, {y, ymin, ymax}] Make a density plot of f as a function of x and y
    Plot3D[f, {x, xmin, xmax}, {y, ymin, ymax}] Make a three-dimensional plot of f as a function of the variables x and y
    ParametricPlot[{fx, fy}, {t, tmin, tmax}] Make a parametric plot
    ParametricPlot[{{fx, fy}, {gx, gy}, ...}, {t, tmin, tmax}] Plot several parametric curves together
    ParametricPlot3D[{fx, fy, fx}, {t, tmin, tmax}] Make a parametric plot of a three-dimensional curve
    ParametricPlot3D[{fx, fy, fz}, {t, tmin, tmax}, {u, umin, umax}] Make a parametric plot of a three-dimensional surface
    ParametricPlot3D[{fx, fy, fz}, {gx, hy, gz}, ...] Plot several objects together

  • A few examples of the above functions:

    Plot[x^2, {x, 0, 10}] document image - no alt tag available. sorry
    Plot3D[Exp[x^2+y^2], {x,-2,2}, {y,-2,2}] document image - no alt tag available. sorry
    ParametricPlot3D[{Cos[t] (3+Cos[u]), Sin[t] (3+Cos[u]), Sin[u]}, {t, 0, 2Pi, {u, 0, 2Pi}] document image - no alt tag available. sorry

  • For attractive examples of some more complicated uses of these graphics functions, have a look at the Graphics Gallery in the Help Browser by choosing the Demos tab and looking under Graphics Gallery.

End Comments

I hope it has become apparent that Mathematica is a really easy program to use. Important things you should take away from this are:

  • Functions begin with a CAPITAL letter.

  • Arguments of functions use SQUARE brackets.

  • Statements end with a semi-colon ONLY if you don't want output.

  • You press SHIFT-return to execute input

  • Once you've got these down, you can just refer to the Mathematica Help for the appropriate function name and arguments. Get friendly with the Help! It is definitely worth your time to spend a few moments browsing though it, especially through all the add-on packages. Every time you do, you'll learn about additional Mathematica functions.

  • Contact information for Wolfram Research and Mathematica:

    Web site http://www.wolfram.com
    General email:
    Technical support: , http://support.wolfram.com
    Newsgroup: comp.soft-sys.math.mathematica, http://forums.wolfram.com/mathgroup
    Bookstore: http://store.wolfram.com

Additional help

[ http://help.unc.edu/?id=4203 ] More on Mathematica

[ http://its.unc.edu/research-computing.html ] Research Computing home page

Copyright 2002-2007 The University of North Carolina at Chapel Hill.

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 United States License.

Post a Comment

This form is for document feedback. If you need technical assistance, and are affiliated with UNC-Chapel Hill, please Submit a Help Request
Optional
Optional
So that we may contact you.
Do not fill out this form, this is a spam trap.
Top
University of North Carolina - Chapel Hill