Introduction to Mathematica

A first draft for Physics 221A, Fall 2004.
Written by Daniel Larson (05-Sep-2004)

General advice

The purpose of this notebook is to let you quickly see some examples of how one can do calculations using Mathematica. As with any computer program, there are quirks of syntax that take some getting used to, and the easiest way to learn the ins and outs is by trying to use the program yourself. The fastest way to start doing that is by looking at and starting to modify some examples.

These examples are by no means comprehensive. If you would like a more detailed introduction, open up the "Help Browser" in the "Help" menu at the upper right of the window; then choose the "Getting Started" subtopic.

Mathematica is very powerful, but it can also make calculations a bit opaque. I recommend keeping your notebooks as neat as possible and using descriptive variable names. If the result of your computation looks mysterious, you really had better double check to make sure you know what Mathematica is doing. I strongly recommend doing every step in multiple ways so that you are certain that Mathematica is doing exactly what you want it to.

To collapse these ramblings, and to view the examples below, simply double click in the right-most blue bracket at the right of this screen.

Basic Calculations and Variables

Simple manipulations in Mathematica are relatively intuitive. You provide input by typing in a "cell", indicated by the brackets on the right side of the window. To evaluate the cell, you type "Shift + Enter". (For these examples, I've provided the input... all you have to do is click in the cell next to the numbers and then evaluate with "Shift+Enter".)

1 + 1

8*5/(3!) - 17

Mathematica likes to give exact expressions if it can. If you want numerical values, you use the function "N", which can be done in several ways. Functions in Mathematica always start with a capital letter and take arguments in square brackets "[...]". Simple functions can come after an expression using "//" which acts kind of like a pipe "|" in unix.

N[8*5/(3!) - 17]

8*5/(3!) - 17 // N

If you want to learn more about a function, just open up the help browser (upper right menu) where you will find tons of information and documentation.

Variables are any strings starting with a letter and that do not have any spaces. They can be assigned values using a single "=".

a

a = 3

a

myNewVariable1 =  10^2
myNewVariable2 = 3*5

myNewVariable1/myNewVariable2

Spaces between variable names represents multiplication, so be careful!

b = 8

a
b
ab
a b

a b  ==  a*b

A couple of variables are already defined, such as "I", "E", and "Pi".

I
E
Pi

N[E]
Pi // N

You can't reassign these variables:

Pi = 7

Pi // N

Plotting and Defining Functions

Here are some examples to show you the names of some Mathematica functions and how to use them. There are intentionally some commands that produce errors... hopefully you can see why and how I fixed them.

Sin[Pi/3]

Plot[Sin[x], {x, 0, 4  Pi}]

taylor1 = Series[Sin[x], {x, 0, 3}]

Plot[taylor1, {x, 0, 4  Pi}]

taylor2 = Normal[taylor1]

Plot[taylor2, {x, 0, 4  Pi}, Frame -> True]

taylor3 = Normal[Series[Sin[x], {x, 0, 10}]]

Plot[{Sin[x], taylor2, taylor3}, {x, 0, 2  Pi}, Axes -> False,  
      PlotStyle -> {RGBColor[1, 0, 0], RGBColor[0, 1, 0], 
          RGBColor[0, 0, 1]}]

You can also define functions. Here is an example to show you the syntax.

myFunction[x_, y_] = Sin[x*y]

myFunction[Pi, 1]

myFunction[Pi, 1/2]
myFunction[a, c]

(Remember, we defined "a" earlier!)

Plot3D[myFunction[x, y], {x, 0, 3  Pi/2}, {y, 0, 3  Pi/2}]

ContourPlot[
      myFunction[x, y], {x, 0, 3  Pi/2}, {y, 0, 3  Pi/2}]

Derivatives and Integrals

Let's clear the variable "a":

a

a =.

a

f[z_] = z^5  Exp[-a z]

f[w]

D[f[w], w]

Integrate[f[r], {r, 0, Infinity}]

Mathematica tries to be as exact as possible, not necessarily assuming that "a" is real.

Integrate[f[r], {r, 0, Infinity}, 
      Assumptions -> {a > 0}]

Integrate[f[r], {r, 0, 5}, Assumptions -> {a > 0}]

Expand[%]

"%" means the last output... be very careful, because "%" changes every time, so if you go back later and re-evaluate the cell you'll likely get a different result.

Integrate[Exp[-a x^2/2], {x, 0, ∞}, 
      Assumptions -> {a > 0}]

Simplify[%]

FullSimplify[%]

PowerExpand[%] // FullSimplify

The above expression is a notorious example of an expression that Mathematica doesn't simplify well...  the usual tricks "Simplify", "FullSimplify", and "PowerExpand" don't work and I haven't yet found something that works.

value = 
      Integrate[Exp[-a x^2/2], {x, 0, 10}, 
        Assumptions -> {a > 0}]

Don't worry about the error message... Mathematica variables are case sensitive. "Value" has some built-in meaning, but "value" is distinct.

N[value]

The "/." allows you take an expression and substitute values for the variables without having to actually assign the variable a value. The right arrow is formed by a "-" and ">".

value /. a -> 3

N[value /. a -> 3]

Equation solving

soln = Solve[x^2 == 5, x]

Mathematica likes to store things in lists of lists. You can extract an element using double brackets, "[[...]]".

soln
soln[[1]]
soln[[2]]
soln[[2, 1]]

x^2 /. soln[[2]]

You can also solve differential equations, with or without initial conditions. Mathematica understands "primes" as derivatives. The "C[1]" in the output is a constant of integration.

DSolve[x''[t] == -k*x[t], x[t], t]

DSolve[{x''[t] == -k*x[t], x'[0] == 0, 
        x[0] == 3}, x[t], t]

You can also solve equations numerically. The result is an "interpolating function" that you can evaluate at a specific point or plot.

result = 
      NDSolve[{x''[t] == -3 x[t] + y[t], y''[
              t] == -y[t], x'[0] == 1, 
          x[0] == 0, y'[0] == 0, y[0] == 1}, {x[t], 
          y[t]}, {t, 0, 10}]

x[t] /. result /. t -> 7
x[t] /. result[[1]] /. t -> 7
y[t] /. result[[1]] /. t -> 7

Plot[{x[t], y[t]}, {t, 0, 10}]

Plot[{x[t] /. result, y[t] /. result}, {t, 0, 10}]

Matrices and vectors

A matrix can be represented by a list of lists.

myMatrix = {{a, b}, {c, d}}

Oops... maybe "b" is still assigned a value.

b =. 
b
myMatrix

Hmmm... "b" is redefined, but we haven't redefined "myMatrix".

myMatrix = {{a, b}, {c, d}}

That's better.

myMatrix // MatrixForm

vec1 = {x, y}

Note the difference between the two following types of multiplication!

myMatrix*vec1
% // MatrixForm

myMatrix . vec1
% // MatrixForm

Transpose[myMatrix] // MatrixForm

evals = Eigenvalues[myMatrix]

Eigenvectors[myMatrix]

together = Eigensystem[myMatrix]

?Together

(Nice to know! Maybe that "possible spelling error" isn't as annoying as I thought... it helps you learn about new commands!)

together[[1]]
together[[2]]
together[[2, 1]] // MatrixForm

myMatrix . together[[2, 1]] - 
      evals[[1]]*together[[2, 1]]

Simplify[%]