Introduction to Mathematica
Interface and Basics

The Class

Violeta M. Ivanova, Ph.D., Educational Technology Consultant, MIT Academic Computing
Contact: N42-250J, 617-252-1383, violeta@mit . edu
Class materials: http://web.mit.edu/acmath/math/IntroMathematica
Web site: http://web.mit.edu/violeta/www/IAP2006

Schedule

Mathematica Interface and Basics, V. M. Ivanova
Numeric and Symbolic Computations with Mathematica, W. C. Carter
Mathematica for Linear Algebra and Calculus, W. C. Carter
Graphics in Mathematica, V. M. Ivanova
Mathematica Programming, V. M. Ivanova

References

Mathematica 5.2 Documentation, Wolfram Research Inc., http://documents.wolfram.com/mathematica
W. C. Carter, MIT 3.016 Lecture Notebooks, http://pruffle.mit.edu/3.016, ccarter@mit.edu
S. Hassani, "Mathematical Methods: Using Mathematica for Students in Physics and Related Fields"
J. Glynn and T. Gray, "The Beginner's Guide to Mathematica Version 4" http://www.mathware.com

Notebooks

Front End and Kernel

Mathematica consists of two major components: the kernel and the front end. The kernel is the computational engine where commands are processed. The kernel can reside on your computer or it may reside somewhere else, e.g. on a supercomputer. The front end resides on your computer and includes the windows where you type your commands. These windows or notebooks are Mathematica's interface with the kernel.

Notebooks

Notebooks are interactive Mathematica documents, which consist of cells that contain text, calculations, and graphics. You can read notebooks either in Mathematica or in the Math Reader. You can edit notebooks and evaluate the commands in them only in Mathematica. Notebooks can be saved in files with an extension .nb.
Cells are indicated by brackets on the right. This cell is a text cell in the notebook called InterfaceBasics.nb.  If you press Enter, you go to a new line. You can type formulae, but you cannot compute in text cells.
The input for Mathematica to evaluate goes in input cells. To create a new input cell, click outside an existing cell and start typing. When you have finished, to evaluate the input, hold down the Shift key while hitting the Return key. The cursor can be anywhere in the input cell when you press Shift+Return. 
For example, the following is an input cell:

5  +  6

When you press Shift+Return, Mathematica evaluates the input and puts the result in an output cell immediately underneath. The In[n]:= and Out[n]:= labels are added automatically. You can edit existing input and press Shift+Return to re-evaluate it. The new result replaces the old one in the output cell. 
The default cell is an input cell. To create another type of cell, use the Format->Style menu to select its type first.

Input Forms

You can enter input commands in InputForm, StandardForm, or TraditionalForm. 
The InputForm is the original, unambiguous, plain-text only, input notation of Mathematica, which looks like this:

A = (x+2)^2*(y+3)/2+c

The TraditionalForm is the traditional mathematical notation, which is a relatively new feature in Mathematica and a rather unique feature for a computational software. It looks like this:

A = (1/2) (y + 3) (((x + 2))^2) + c

The StandardForm allows you to enter input in both InputForm and TraditionalForm to avoid any ambiguity. 
The default in Mathematica 5.2 is the StandardForm. To shift between input forms, use the Cell->Convert To menu. In order to type input in TraditionalForm, generally you will need to use a typesetting palette.

Palettes

Various palettes for creating input can be opened from the File->Palette menu. The BasicTypesetting palette enables input in traditional mathematical notation. Very useful palettes are also the BasicCalculations, BasicInput, and AlgebraicManipulation palettes, which provide shortcuts for entering commonly used functions and expressions.

Style Sheets

Mathematica allows you to customize the look of your notebooks by using a design templates or even by creating your own style sheet. This notebook uses the Classroom style sheet. To select another design template, use the Format->Style Sheet menu.

Variables and Operators

Variable names

Start with a letter, and use only alphanumeric characters in naming your variables. Non-alphanumeric characters, including not only the algebraic operators such as like -, +, *, /, and ^, but also characters such as %, :, _, and @, are reserved for the Mathematica language. Variable names are case-dependent, i.e. X is different from x.

Assignment =

The assignment operator = is used for assigning values to variables.

x = 5
y = x + 1
(Sqrt[(x^2) + (y^2)])

Values assigned to variables are kept until they are explicitly cleared or until the end of the  Mathematica session. For example, if not cleared, x and y in the expression below will still have the numerical values they were assigned above:

(x^2) + (y^3)

Therefore, clear the values of variables as soon as you have finished using them.

Clear[x, y]
(x^2) + (y^3)

Replacement operator /.

In Mathematica, you can avoid using inadvertently values of variables by applying transformation rules. In the following input, /. x→3 is a transformation rule: it uses x=3 to compute the expression, but does not assign a value to x in the process.

(x^5) + (x^4) + (x^2) + 1 /. x -> 
        3

Variable Types

Mathematica can compute expressions with integers, real and complex numbers, and even fractions.

anInteger = (19^50)
Head[anInteger]

If you put an explicit decimal point in your input, then Mathematica gives you an approximate numerical result. Very large and very small numbers are then shown in exponential notation.

aRealNumber = (19. ^50)
Head[aRealNumber]

Another way to do that is by using // N after the expression that is being evaluated, or by using the N[] function.

aRealOne = N[(19^50)]
Head[aRealOne]
aRealTwo = N[(19^50)]
Head[aRealTwo]

aComplexNumber = 2 + I
Head[aComplexNumber]

aFraction = (2/3) + (4/5)
Head[aFraction]

aStringVariable = "hello"
Head[aStringVariable]

Brackets and other operators

Operators such as +, -, /, *, and ^ are self-explanatory. In Mathematica you can also use a space to indicate multiplication. For example, the product of a and b can be written as a b or a*b. Without a space ab is a single variable.

a = 5;  b = 2;  ab = 3;  c  =  a b

Parentheses ( ) are used to group operations, usually to change the order of precedence of algebraic operators.

(((π + 3. ))^2)

Square brackets [ ] are used to enclose the arguments of functions.

Sqrt[x]
Clear[x]

Typing a semicolon ; at the end of an input statement prevents output from being displayed.

(2^20) (3^20);

You can use % to stand for the result of the last calculation you did. This works regardless of where that calculation appears - whether in the same notebook or another one.

\(\@%\)

Pre-defined variables

Using any of the following variable names will over-write their built-in values. You can enter the names of a pre-defined variable using Esc variablename Esc (for example, Exc pi Esc or Esc ii Esc), or by typing its name in Input Form, or by using the typesetting palette (the last one may cause ambiguity).

Pi
π
E
E
I
I

If you over-write a pre-defined variable by mistake, use Clear[]: this will return its value to the built-in value.

Pi  =  8
Clear[Pi]
Pi

Numeric and Symbolic Computation

Mathematica is built on the unifying idea that everything can be represented as a symbolic expression. All symbolic expressions are built from combinations of the basic form head[argumen1, argumen2, ...]. For example:

Plus[a,  b]
List[1,  2,  3]
Plus[Power[x, 2],  x]
Show[Graphics[Circle[{1,  0},  2]]]

You do not need to learn that notation in order to use Mathematica! It is much easier to enter expressions using familiar algebraic operators or the math typesetting palettes. But knowing that everything is translated into symbolic expressions by Mathematica can help you understand that: (1) all functions can be nested; (2) practically every computation is possible in Mathematica; and (3) any construct, e.g. any engineering or scientific expression, can be added to Mathematica. 
Symbolic expressions work on numbers as well as on non-numeric variables. For example:

Expand[(((a + b))^3)]
Simplify[Cos[x]^4 - Sin[x]^4]
Factor[
      (a^3) + 3 (a^2) b + 3 a (b^2) + (b^3)]
Together[1/x + 1/(1 + x)]

FullSimplify[Gamma[z] Gamma[1 - z]]
ExpandAll[((((a + b))^2)/(((c + d))^3))]

Lists and Tables

List Construction

Lists are general objects that represent collections of expressions. Use curly brackets {} to enclose the elements of lists. For example, {a, b, c} represents a vector. {{a, b}, {c, d}} represents a matrix. Nested lists can be used to represent tensors.
Lists can include elements of different types, i.e. numbers, symbols, complex numbers, strings.
Most built-in mathematical functions are Listable and can be  "threaded" over lists, acting separately on each list element.

{1, 2, 3, 4, 5}
x^%
x^{1, 3, 5}
% /. x -> 2
N[Sqrt[%]]

Function Table[] is commonly used to construct lists.

L1 = Table[(x^2), {x, 1, 5}]
L2 = Table[(x^i), {i, 1, 5}]
L3 = Table[Cos[x i π], {i, 1, 6}]
L4 = Table[(x^i) + (y^j), {i, 1, 3}, {j, 1, 5}]

Lists can be shown in TableForm or MatrixForm.

M = MatrixForm[L4]
T = TableForm[L4]

List Operations

Use [[]] to access the elements of a list.

L = Table[{a, b, c}^i, {i, 1, 4}]
MatrixForm[L]
L[[1, 2]]
L[[1, All]]
MatrixForm[
      L[[Range[2, 4], {1, 
          3}]]]

Other useful functions are Length[], Dimensions, Drop[], and Append[].

Length[L]
Dimensions[L]
Alist = Drop[L, 1]
Blist = {x, y, z}
TableForm[Append[Alist, Blist]]
TableForm[MapThread[Append, {Alist, Blist}]]

Functions and Equations

Functions and delayed assignment :=

The following defines a function f. Note the underscore in x_ and the := sign.

f[x_] := (Sqrt[(x^2) + 1])

You can give variables, numbers, or symbolic expressions as arguments to f.

{ f[x], f[2. ], f[a + b] }

You can also apply functions to lists to create new lists.

f[ {y,  3. ,  c + d} ]

Functions can have different definitions for different types of variables.

g[x_Integer] := N[(Sqrt[x])]
g[x_Real] := (Sqrt[x])
g[x_Complex] := "complex number"
g[x_String] := "non-numeric input"
g[37]
g[25.6]
g[(Sqrt[-1])]
g["hello"]

And, of course, functions can have more than one variables.

powerTwo[x_, y_, z_] := (x^2) + (y^2) + (z^2)
powerTwo[x, y, z]
powerTwo[1, 2, 3]
powerTwo[a, b, 4]

Equations and equality assignment ==

Equations are written with the equality assignment == notation. 
Function Solve[equations, variables] solves a set of equations for a set of variables. Solutions are returned as rules of the form variable1 -> value1, variable2 -> value2, etc.

Solve[x^2 + x == a, x]
Solve[x^2 + x == a, x] /. a -> 2

You can solve equations involving more than one variable. In the output, each sublist represents one solution.

Solve[{x == y + 2*a*y, y == 9 + 2*x}, {x, y}]
Solve[{x^2 - k^2 == 0, y^2 == x^2}, {x, y}] // TableForm

Solve can also handle equations involving more complicated functions.

Solve[Log[x + Sqrt[a + x^2]] == b, x]

NSolve solves equations numerically. For example, NSolve can solve a system of polynomial equations:

NSolve[{x^3  -  y  == 0,  
          y^2   -  x^2  ==  1},  {x,  y}]  //  
      TableForm

Graphics

Here are some commonly used Mathematica plotting functions. The range of a plot is specified by lists.

Plot[(x^2) + x + 1, {x, 0, 10}]; 
Plot[{Sin[x], Cos[x]}, {x, 0, 2 π}];

ParametricPlot[{(t^2), t}, {t, -2, 2}]

Plot3D[
      Cos[x]^2 + Sin[y], {x, 0, 2 π}, {y, 0, 2 π}]

Work Directory

$Path gives the default directories to search when attempting to find an external file.

$Path

Function Directory[] gives the current working directory.

Directory[]

Function SetDirectory["directory"] sets the current working directory to directory.

SetDirectory["/Users/violetaivanova/IAP2006/\
IntroMathematica/Interface_Basics"]

File Import and Export

Function Import["filename.ext"] imports data or an image from the file filename with extension ext. Mathematica recognizes many formats, e.g. TXT, DAT, CSV, etc. for text, and JPG, GIF, TIFF, etc. for images.

Images

"Sunrise in Canyon Escalera" photo © 2003 V. M. Ivanova

image  =  Import["escalera.jpg"]

Use the Show command to display the imported image. The result is a Mathematica Graphics object.

Show[image]

Use Export["filename.ext", graphicsobject] to save a Graphics object in a file.

Export["sunrise.tif",  image]

Spreadsheets

Mathematica imports spreadsheet data as Lists. To import in another format, use the Import function with an additional argument: Import["filename.ext", "format"]. 
To suppress output during command evaluation, put a semicolon ; after the command. For example, the file XYZpoints.txt has more than 3000 elements. To following command imports the file without displaying them.

data  =  
        Import["XYZpoints.txt",  "Table"];

Summary Mathematica Notation

Quick Reference

({{All built-in functions start with a capital letter.,            Sqrt[6]}})

({{Use . or N to get decimal values from interegs.,            Sqrt[6. ] or Sqrt[6]//N}})

({{Use ; to supress long output during evaluation. ,           x  =  100!;}})

({{Use [ ] to enclose function arguments. ,           Range[1, 10]}})

({{Functions can be nested. ,           Integrate[Sqrt[t], t]}})

({{Use palletes for mathematics typesetting. ,           ∫(Sqrt[t]) dt}})

({{Use % to refer to the last computed value. ,           Det[%]}})

({{Use {} to enclose list elements.,           A  =  {1, 2, 3}}})

({{Nested lists represent tables and matrices.,           B  =  {{1, 2},{a,  b}}}})

({{Use [[ ]] to refer to the elements of a list.,           B [[2,  All]]}})

({{Functions and operatos can be applied to lists. ,           {1,  2,  3}  +  5}})

({{Use () to indicate grouping of terms.,            a/(b  +  c)}})

({{Use = to assign a value to a variable. ,           y= 5. or y = x}})

({{Use == to express equality in equations. ,           Solve[x^2 == 3, x]}})

({{Use := to define a function. ,            f[x_] := x^2}})

({{Use x_ to indicate an arbitrary expression named x.,            f[x_] := x^2}})

({{Use /.x -> y  to compute for x=y without assigning the value of y to x.,            x^2 /. x -> 2}})

Mathematica Help Browser

Use the Help->Help Browser menu to open the Mathematica Help Browser.

Or click on any of the links below to view a list of all built-in functions in that category.

({{Numerical Computation, Algebraic Computation, Mathematical Functions}, {Lists and Matrices, Graphics and Sound, Programming}, {Input and Output, Notebooks, System Interface}})