Chris Brown
brownce@kenyon.edu

Mathematica Cheat Sheet

Expanded Version, Updated 2/28/2005

Functions

Defining Functions

f[x_] := (x^2) - 1;

Notes: You must use square brackets around the input, both when defining and evaluating the function.  Don't forget the underscore after the x on the left, and the colon before the  =  sign.

Evaluating Functions

f[2]

Mathematica can also apply functions to expressions.

f[x + h]

Note: You must use square brackets around the input.

Mathematica will also allow a post-fix notation.  If you want to apply a function as an afterthought,

2 // f

This is most frequently used when the function adjusts the display of the output in some way.  For instance, the built-in function N will give a decimal approximation of an expression.  Compare:

f[1/3]

f[1/3] // N

Identifying Functions

With a large notebook, it may be easy to lose track of which function a particular symbol refers to.  For example, we defined f at least a couple of times in this notebook.  At this point in our work, what is f?  We can use the following command:

?f

If we clear f first, what will happen?

Clear[f];
?f

Notice that no function definition appears; f is now simply a globally defined variable.

Clearing Functions

Sometimes you will want to give a name you have already used to a new function.  It is a good idea to clear the original function and original variable first, using the Clear command.

Clear[f, x]

f[x_] := (x^3) - x

f[2]

Plotting Functions

Plot[f[x], {x, -2, 2}]

To restrict the range of values on the y-axis, use the PlotRange command:

Plot[f[x], {x, -2, 2}, PlotRange -> {-1, 1}]

Lists and Tables

A Short List

A = {1, 1, 2, 3, 5, 8, 13}

Note: To define a list explicitly as in this example, you must use the curly braces { } around the list elements, with commas to separate them.

To output the ith element of a list, write the name of the list and the number i surrounded by double square brackets.

A[[3]]

A[[5]]

An ordered pair is a list with 2 elements.  Here is a point on the graph of f:

{2, f[2]}

List Building

Generally, we will need to work with longer lists (hundreds or thousands of elements).  We will need certain list building tools in Mathematica.  The first is the Range command, which is useful for creating large collections of inputs for functions:

Range[-1, 1, 0.1]

The second is the more general Table command:

Table[i^2, {i, 1, 10}]

Example 1

We build and display a table of values for a function f on x values which are evenly spaced on an interval.

Clear[f, x];
f[x_] := x^3 - x;
xin = Range[-2, 2, 0.5];
data = 
        Table[{xin[[i]], f[xin[[i]]]}, {i, 1, 
            Length[xin]}];
data // TableForm

These commands for table building can be written more compactly as:

Clear[f, x, data];
f[x_] := x^3 - x;
data = 
        Table[{x, f[x]}, {x, -2, 2, 0.5}];
data // TableForm

We can plot a list of ordered pairs, connected by line segments.  Notice the choppiness of the plot; this is due to the small number of data points we are plotting.

ListPlot[data, PlotJoined -> True]

Example 2

We build a table of values to investigate a function near a point.

Clear[f, x, xin, data];
f[x_] := ((x^2 - 4)/(x - 2));
xin = Table[2 + (1/(10^i)), {i, 1, 5}];
data = 
        Table[{xin[[i]], f[xin[[i]]]}, {i, 1, 
            5}];
data // N // TableForm

Here, the use of //N has forced the fractions to be written as decimals.  From this table, we would guess that the limit as \(TraditionalForm\`x -> \(2\^+\)\) of f[x] is 4 (it is; check!).

Algebra

Expressions

An expression is just a collection of variables and arithmetic operations:

a = x^2 - x + 2

Notice that an expression is not a function.  The following attempt to treat a as a function fails.

a[1]

To substitute a value for a variable in an expression, use the  /.  and   ->   ("-" then ">") operators.

a /. x -> 2

You can substitute another expression:

a /. x -> x + h

And, you can substitute for more complicated expressions.  In the following example, Mathematica does not assume that x = (Sqrt[y ]) when y = (x^2), and so just leaves the x term in the expression.

a /. x^2 -> y

Expand, Factor, Collect

b = (x - 1)^2 (x + 2) (x + 3)

Expand[b]

Clear[b];
b = x^2 - 2  x + 1

Factor[b]

Clear[b];
b = 2 x - m x + 7 y - 3 z

Collect[b, x]

Expand and Factor also work on rational expressions, applied to the numerator and denominator separately.

Factor[(x^3 + 3 x^2 +  3  x  + 1)/(x^2 - 4)]

Equations

An equation consists of any two expressions linked by an equality operator.  In Mathematica, the equality operator is a double equal sign   == .

x^2 - 9 == 0

You can give your equation a name, just as with expressions.  This can be confusing at first, because you will be dealing with two different equals signs, the "set equals" sign  =  and the "is equal" sign  == .

eqn = x^3 - x == 0

eqn

Solve

An equation can be solved for a variable using the Solve command.

ans = Solve[eqn, x]

The result will be a list of lists of substitution rules.

ans[[1]]

ans[[2]]

To retrieve the answer as a number, use the substitution operator on the variable.

x /. ans[[1]]

x /. ans[[2]]

Here is a nice piece of code that will change all of the rules to numbers and store them in a list:

(x /. #) & /@ ans

You will need to use the original variable name (in this case, x).  As another example, consider a projectile motion problem in which we are trying to find the time at which the projectile lands on the ground.  We will need to solve

projectile = (Subscript[y, 0]) + (Subscript[v, 0]) t - 1/2 g t^2 == 0;

projectileans = Solve[projectile, t]

The two solutions are (notice the use of the t variable)

myans = (t /. #) & /@ projectileans

If the projectile was thrown from ground level, (Subscript[y, 0]) = 0:

myans = myans /. (Subscript[y, 0]) -> 0

Assuming that (Subscript[v, 0]) > 0 gives:

Simplify[myans, (Subscript[v, 0]) > 0]

Derivatives

Derivatives of Functions and Expressions

Clear[f, x];
f[x_] := x^2 - 1

There are two common notations for differentiation in Mathematica: the prime notation

f'[x]

and the D notation.

D[f[x], x]

The D notation can be typeset using the Basic Input palette symbol ∂

(∂_x) f[x]

It is generally better for our class to use this second method.  This is because we like to work with expressions, and the prime notation only applies to functions.  Consider

h = (Subscript[y, 0]) + (Subscript[v, 0]) t - 1/2 g t^2;

Using the prime notation will not evaluate the derivative of this expression:

h'

But using the ∂ notation will:

(∂_t) h

The Dt notation ("total derivative"):

Clear[f, x];
f[x_] := (x^2);
Dt[f[x], x]

Clear[a];
newder = Dt[a (x^2), x]

Note here that Dt does not assume that a is a constant.  This can be to our advantage...

What if a is a constant?  Then Dt[a, x] = 0, and so we have

newder /. Dt[a, x] -> 0

But what if a = (e^x)?

newder /. a -> (E^x)

We don't have to redefine the derivative every time, just use a different substitution.

When is the total derivative appropriate?  Frequently, we may have an expression in which one variable is implicitly a function of one or more of the remaining variables.  If we use D we may compute the implicit derivative incorrectly:

expr = (x^2) + (y^2) == 1;
D[expr, x]

However, using Dt we have

implicitder = Dt[expr, x]

We can then use the Solve command to compute the derivative of y with respect to x:

soln = Solve[implicitder, Dt[y, x]];
Dt[y, x] /. soln[[1]]

One Last Example

The Tangent Line Problem

Given an equation and a point on the graph of the equation, find the equation of the line tangent to the graph at the given point.

Clear[eqn, a];
eqn = 
        y == (x - 2) (x - 1) (x + 1) (x + 
                2);
a = 2;

sub = Solve[eqn, y];
expr = y /. sub[[1]]

Clear[m, x, b];
tangent = m x + b

m = (∂_x)(expr) /. x -> a

intercepteqn = (expr /. x -> a) == (tangent /. 
            x -> a)

interceptsoln = Solve[intercepteqn, b]

b = b /. interceptsoln[[1]]

tangent

Plot[{expr, tangent}, {x, -3, 3}]

As with many other operations in Mathematica, there is a short way to work this problem, given some extra knowledge.  The first line here is a function TangentAt which returns as a function the equation of the line tangent to the given function f at the given point a.  The remaining lines define the function y and recompute the same tangent line that we computed above.

TangentAt[f_, 
          a_] := (f[
                a] + f'[
                  a] (x - a)) &;
y[
          x_] := (x - 2) (x - 1) (x + 1) (x + 
              2);
z = TangentAt[y, 2];
z[x]

Notes

What else can Mathematica do?  Lots.  Here are a few things that might not show up in a Calculus course that I have found useful:

C style programming:  You can use most of the standard C flow control structures (For, While, If...Then, etc.).  Combined with Mathematica's built-in data structures and mathematics capabilities, these structures will allow you to do everything you would want to do (with math) using C.  As a warning, Mathematica does not seem to have a code optimizer, and so most C code will run more slowly in Mathematica than when compiled in C.  On the plus side, it takes little to no work to code simple data structures and mathematical operations in Mathematica (since they are built-in).  Mathematica also seems to be very good at overloading operators; for discussion of this, look up UpSet in the Mathematica master index.

Probability and Statistics:  The Statistics package contains procedures for common distributions and data manipulation, and Mathematica's I/O procedures allow us to read data from text files (so data can be exported from spreadsheets or databases and imported into Mathematica).

Linear Algebra:  Mathematica treats matrices as lists of lists, and can easily compute determinants, eigenvalues and eigenvectors, etc.

Differential Equations:  The DSolve command will solve some differential equations, and NDSolve will find a numerical solution to some equations.  The solvers seem to be fairly limited when dealing with partial differential equations.

Fourier Analysis: 'Nuff said.