Mathematica Command Glossary


This document primarily covers information about computational commands in Mathematica. You may also be interested in Mathematica 2D Graphics or Mathematica 3D Graphics.

TABLE OF CONTENTS

Examples:

Calculations:

Example: Make Your Own Function

In this example, we are going to define a function, calculate with it, make a table of its values, plot it, and compute its derivative.

Before using variables in Mathematica, it's always a good idea to use the Clear command to make sure your variables don't have any old meanings attached to them:


        Clear [ f, x ]
      

Now we'll define our function, by typing in the formula. We need to use a special form for the left hand side, which includes an underscore after the name of the variable, and a special "colon-equals" sign for the function definition:


        f[x_] := Sin[x] / x
      

To evaluate the function, we just put numbers, or names of numbers, as the argument of the function:


        f[2.0]

        x = 17.4
        f[x]

        f[Pi]
      

Similarly, we can compute the formula for the derivative of the function using a "prime", which is a shortcut for the D (Differentiate) command:


        f'[x]
      
but if x already has a value, we won't get a formula for the derivative, we'll get the value! So try again:

        Clear [ x ]
        f'[x]
      
We can display the function with the Plot command:

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

Back to TABLE OF CONTENTS.

Example: Riemann Sums

A Riemann sum is an estimate of the integral of a function. To compute a Riemann sum, you need an interval [a,b], a function f(x), a number of subintervals to use n, and some way of choosing a sample point in each subinterval.

Usually, the intervals are all the same size, h, in which case


        h = ( b - a ) / n
      
A sensible rule for the sample point would be to use the rightmost point in each interval. If that's what we do, then the first sample point will be a+h, the second one a+2*h and so on up to a+n*h.

Here is a simple example of computing a Riemann sum of a function:


        Clear [ a, b, correct, f, h, i, n, riemann, x ]

        a = 0.0
        b = 5.0

        n = 100
        h = ( b - a ) / n

        f[x_] := Sqrt [ x + 1 ] 

        riemann = 0

        Do [
         {
           x = a + i * h,
           riemann = riemann + h * f[x]
         },
         { i, 1, n, 1 } ]

        Print [ "The Riemann sum is ", N[riemann] ]

        correct = Integrate [ f[x], { x, a, b } ]

        Print [ "The exact integral is ", N[correct] ]
      

Now, if you're going to use a Riemann sum a lot, it might be nice to be able to convince Mathematica to let you define a new command that is similar to Integrate, something like:


        rightRiemannSum [ f[x], { x, a, b, n } ]
      
To see how to do this, look at Advanced Functions.

Back to TABLE OF CONTENTS.

Example: The Euler Method for Differential Equations (using Mathematica functions)

A typical problem in differential equations wants to estimate the value of a function if we know its value at one point, and a formula for its derivative. For example, we might have:


        y(5.0) = 0.5
        y'(x) = cos(x)
      

Euler's method uses the solution value at one point, and the derivative formula, to estimate the solution at a nearby point. In particular, it is approximately true that


        y(x+dx) = y(x) + dx * y'(x)
      

Thus, to solve a differential equation, we start at y(x), use Euler's method to estimate the solution at y(x+h), use that value to estimate the solution at y(x+2h) and so on.

In other words, the solution of this problem by Euler's method results in a table, or list of values. We need a way to store these values so that we can examine or plot them later. For this example, we will use a feature of Mathematica that allows us to define a function f(x) at just a selected set of points. We'll have to be careful to store all the values we need.

We're going to define two functions x[i] and y[i]. The values of x are simply evenly spaced values starting at the initial point. The values of y are the corresponding values determined by the Euler method:


        Clear [ x, y, h, i ]

        x[1] = 5.0;
        y[1] = 0.5;
        h = 0.1;

        Do [ {
             x[i+1] = x[i] + h,
             y[i+1] = y[i] + h * Cos[x[i]]
            }, { i, 1, 120 } ]
      

Now we can plot our results, making sure we only refer to values of x and y that we have defined:


        Clear [ pairs ]
        pairs = Table [ { x[i], y[i] }, { i, 1, 121 } ]
  
        ListPlot [ pairs, PlotJoined -> True ]
      

Back to TABLE OF CONTENTS.

Example: The Euler Method for Differential Equations (using Mathematica lists)

We've already discussed how to set up Euler's method, by using a sort of functional notation. Now we are going to repeat the problem, but using Mathematica lists. The idea is still the same - we set a new x value, compute the corresponding y value, and save the two quantities somewhere.

The difference is that now we are going to use Mathematica's list format instead, which is really more appropriate for this kind of data. In particular, in a list we are simply storing values; using a function defintion, we were actually storing rules, which are more complicated to store and evaluate.

We're going to define two lists x and y. We start out with just one value in each list (the initial conditions). Then we use the Append command to add our next pair of values to the list.


        Clear [ x, y, h, i ]

        x = { 5.0 };
        y = { 0.5 };
        h = 0.1;

        Do [ {
             x = Append [ x, x[[i]] + h ],
             y = Append [ y, y[[i]] + h * Cos[ x[[i]] ] ],
            }, { i, 1, 120 } ]
      

Now we can plot our results:


        Clear [pairs ]
        pairs = Table [ { x[[i]], y[[i]] }, { i, 1, 121 } ]
  
        ListPlot [ pairs, PlotJoined -> True ]
      

Back to TABLE OF CONTENTS.

Advanced Functions

The simplest user-defined functions are the "one-liners", where the quantity of interest can be computed by a single formula. Such formulas are discussed under Simple Functions.

In some cases, you may find it impossible to define the function's value in a single simple formula. Instead, you may need to carry out several steps of computation, using temporary variables.

You may want several input values, and you may want the user to group some of those input values in curly brackets.

Here is an example of a user-defined function, which computes the left Riemann sum approximation to the integral of a function f[x] from a to b, using n intervals:


        Clear[f, leftRsum, x]

        leftRsum[ f_, {x_, a_, b_, n_} ] := 
          Block[ 
            {approx, delx, i},
            delx = (b-a)/n ;
            approx = N[ Sum[ (f /. x->a+delx*i )*delx, {i,0,n-1}] ]
          ]
      

In this example, the first line defines the name of the function to be leftRsum, with 5 arguments, that is, values to be supplied by the user, and to be represented for now by symbolic names. The last four arguments must be enclosed in curly brackets.

The Block command marks the beginning of a group of commands that will carry out the procedure named leftRsum.

The statement {approx, delx, i} defines the set of local variables, that is, the names of variables which will be set and used within the procedure, but which are not function arguments, and which should not alter the values of variables with the same name, defined outside the procedure.

The first assignment command has a semicolon after it to suppress output. The value returned by the function will be the last value computed, namely, the value of approx.

The assignment of approx carries out the Riemann approximation, and causes the function leftRsum to return this value.

As an example of how such a routine might be used, consider the following commands:


        f[x_] := x^2
        leftRsum[ f[x], {x, 0,  10, 5} ]
      

For other examples of this kind of function, see the discussion of Cube Roots or Polar Grids.

Back to TABLE OF CONTENTS.

Apart

A polynomial fraction p(x)/q(x) is said to be improper if the degree of p(x) is greater than or equal to that of q(x).

The Apart command can be used to replace a polynomial fraction by a "whole" part, and a new fraction with the same denominator, but a "proper" numerator. This is similar to changing the "improper" fraction 17/5 to 3 + 2/5.

The Apart command, applied to a polynomial fraction, is essentially carrying out the method of synthetic division. Synthetic division is a useful simplification, and is mandatory before applying the method of Partial Fractions to an improper polynomial fraction.


        Clear[x]

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

In the next example, we can see that Mathematica is not only dividing out the improper part of the polynomial fraction, but is also factoring the denominator and applying the method of Partial Fractions:


        Apart[ (x^5+4x^4+2x^3-7x^2+4x+1) / ( (x^2+1) * (x+3)^2 ) ]
      

The command Together reverses the operation of Apart.

Back to TABLE OF CONTENTS.

Assignment Statements

The easiest way to give a variable a value uses a single equal sign, as in x=1. This causes Mathematica to find the value of the right hand side of the equals sign, and assign that value to the variable named on the left hand side.

In the following example, we assign a value to x, and then use that value as part of the definition of the new value of y:


        Clear[x, y]

        x = 2;
        y = 10*x+1
      

When a single equals sign is used in an assignment, then the variable on the left hand side is given a value immediately. If the quantities on the right hand side are later changed, this will not affect the left hand side. For instance, let's set x to 1, and set y to be two times x, using a single ("immediate") equals sign:


        x = 1;
        y = 2*x;
        x
        y
      

Now let's change x to 10. Does y change to 20, or stay at 2?


        x = 10;
        x
        y
      

If you want to specify that y should change whenever x changes, then you need to replace the single equals sign by the combination "colon-equals". which enforces a relationship "forever":


        x = 1;
        y := 2*x;
        x
        y
      

Now, when we change x to 10, the value of y will change as well:


        x = 10;
        x
        y
      

The double equals sign is used when describing a mathematical equation, rather than an assignment. Thus, to ask the command Solve to find the values of x that make a certain equation true, we write


        Solve [ 4x+2y == 3z-1, x ]
      

The double equals sign tells Mathematica that we are not trying to assign a value to the quantity 4x+2y, but trying to find values of the variable x that make this relationship true.

Often you don't want to assign a single value, but to describe a functional relationship. To see how to do this, refer to Simple Functions.

To see how to assign values to a vector or matrix, refer to Lists of Data.

Back to TABLE OF CONTENTS.

Clear

The Clear command tells Mathematica to "forget" anything you may have said about a variable or formula, allowing you to redefine it or use it in a new way.

Clearing out old definitions is important, because the commands D (Differentiate), Integrate, and Plot will not work properly if the x argument has been previously assigned a numerical value. Here is a sample Clear command:


        Clear[x]
      

Here is a case where Clear is necessary. Because x is set to 1, the D command cannot be carried out properly; it thinks x is the same as the number 1, and so you can't differentiate with respect to it. But once the Clear command is issued, x is understood to be a "dummy" variable:


        x = 1

        D[Sin[x],x]

        Clear[x]

        D[Sin[x], x]
      

In this document, we use Clear as the first command in every example, so that variables left over from other examples won't affect the current example.

Back to TABLE OF CONTENTS.

Comments

When you are using Mathematica to solve a homework problem, it can be important to explain what you're doing, or to "annotate" your results. There are three simple things you can do.

First, you can use text cells. A text cell is a part of a Mathematica notebook that is set aside for text, rather than commands. To make a text cell, you simply start a new cell, and then select the cell in the usual way, by clicking in the little cell marker in the right hand margin. Then, go to the Style menu, then the Cell Style submenu, and choose Text. From now on, anything you type in this particular cell will be considered text. Mathematica will print it in plain style rather than boldface, and won't try to execute your sentences as commands.

The second thing you can do is simpler, though less pretty. You can cause Mathematica to ignore a piece of text by marking it as a "comment". You begin a comment with the symbols (* and end with *). Thus, Mathematica won't be confused by the following commands:


        Clear[area, r]

        r = 4

        (* This command computes the area of the circle! *)

        area = Pi * r^2
      

The third thing you can do to comment your commands is simply to use short strings of text, marked off by double quotes, to add labels or explanations to the numbers you compute. In this case, the quoted string will actually be printed out right next to the number you compute:


        area = N[Pi * r^2] " is the area of the circle."
      

This is not always a great solution. For one thing, you can't do any more calculations with area, because its value is not a number; it's a number followed by a string. For another, Mathematica has many rules for rearranging results that may hurt your intended output. For instance, consider the output of this command:


        area = Pi * r^2 " is the area of the circle."
      

Back to TABLE OF CONTENTS.

Complex Numbers

Mathematica recognizes the symbol I as the complex unit, the square root of -1. Thus, to indicate a complex number, you simply write something like:


        x = 7 + 12 I
      

Note that Mathematica will often present complex numbers as the results of an operation on real numbers, when you neither expect nor want such results. If you merely want the value "-2" when you ask for the cube root of -8, you're in for a shock if you type


        (-8)^(1/3)
      

Similarly, when Mathematica uses high-powered techniques on simple problems, it will return inexplicable results.


        Integrate [ Sqrt [ 1 + x^3 ], { x, 0, 4 } ]
      
returns a complex value. But

        Integrate [ ( 1 + x^3 )^0.5, { x, 0, 4 } ]
      
returns the value you were probably expecting.

Also, in some cases, the results of commands like Solve, applied to a real equation with real roots, returns a complex number with a very small imaginary part. This is just an artefact of the underlying algorithm being employed, and the tiny imaginary part can be safely ignored.

Back to TABLE OF CONTENTS.

Cross (Vector Cross Product)

The Cross command allows you to take the cross product of two vectors of the same dimension, which results in a third vector, perpendicular to the first two, and having length equal to the area of the parallelogram defined by the vectors.

Here is an example of computing a cross product:


        Clear [ x, y ]
        x = { 1, 2, 3 }
        y = { 3, 2, 0 }
        result = Cross [ x, y ]
      

Back to TABLE OF CONTENTS.

Cube Roots

We know that negative numbers don't have square roots - at least not in the real number system, so we are not surprised that Mathematica will not plot the Sqrt function over a negative range, and returns a complex value for the square root of -3.

However, we do expect that negative numbers have a cube root, and so it is very surprising to see that Mathematica has a strange idea about this:


        N[ (-1)^(1/3) ]
      

And because Mathematica returns complex values for such cube roots, you can't plot the cube root function the way you might like:


        (* This won't work! *)
        Plot[ x^(1/3), {x,-2,2}]
      

However, it is fairly easy to set up a function that returns the cube root we expect:


        Clear[cuberoot]

        cuberoot[ x_ ] :=
          Block[ 
            {value},
            value = Sign[x] * (Abs[x])^(1/3)
          ]
      

This function allows us to compute the cube roots we expect:


        cuberoot [ -1 ]
      
and to plot the whole function:

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

The same problem occurs for all odd roots of negative numbers, and can be corrected similarly.

A simpler approach is simply to use those nasty decimal numbers. Mathematica will shed a lot of its sophistication the minute it sees you're only expecting an approximate or numeric answer:


        (* This will work! *)
        Plot[ x^(1.0/3.0), {x,-2,2}]
      

Back to TABLE OF CONTENTS.

D (Differentiate)

The command D[ f[x], x] will differentiate the formula or expression f[x] with respect to the variable x:


        Clear[f, x]

        D[ x^2+2*x+1, x]

        f[x_] := Cos[x]+x

        D[f[x],x]
      

The same command can compute higher order derivatives:


        D[ x^2+2*x+1, {x,2} ]
      

The same command can compute a partial derivative:


        D[ x^2+2*x*y+y^3, y ]
      
or a higher order partial derivative:

        D[ x^2+2*x*y+y^3, { x, 2 } ]
      
or a mixed partial derivative:

        D[ x^2+2*x*y+y^3, x, y ]
      
or a higher order mixed partial derivative:

        D[ x^2+2*x*y+y^3, { x, 2 }, y ]
      

The D command will not work properly if the (symbolic) variable of differentiation has been assigned a numeric value. In such cases, you must first use the command Clear, to "free up" the variable.


        x = 1

        D[Cos[x],x]
 
        Clear[x]

        D[Cos[x],x]
      

If you have written your expression as a function of a variable, then you may also compute the derivative using an apostrophe or "prime", while the second derivative uses two primes:


        f[x_] := Cos[x]+x
        f'[x]
        f"[x]
      

You can use f'[x] in the commands Plot or Solve.


        f[x_] := Sin[x]
        Plot [ f'[x], {x, 0, Pi} ]
      

You may be interested in seeing the example Plot and D Don't Mix.

Back to TABLE OF CONTENTS.

Do

The Do command allows you to make a loop that repeats one or more operations.

The format of the Do command is


        Do [ 
          { command1,
            command2,
            ...
            last command } ,  
        { counter, start-value, end-value, increment} ]
      

The following Do loop calculates the square of the odd numbers between 1 and 9 and then prints out the number and its square.


        Clear[n, nsquare]

        Do [ 
          { nsquare = n^2,
            Print ["n=", n, "   n squared= ",nsquare] }, 
          {n, 1, 9, 2} ] }
      

In this Do loop, the commands to be repeated are grouped inside the curly brackets. (If there is only one command, you don't need the brackets). After the commands comes an iterator, similar to what you've seen for the Table command. This tells Mathematica

The Do command can carry out a simple method of approximating the solution of a differential equation. (Of course, the DSolve command is better, if you can use it.) Let h, v, and a represent the height, velocity, and acceleration of a ball under the influence of gravity.

Set the initial values at time 0:


        Clear[a, dt, h, v]

        h[0] = 200;
        v[0] = 50;
        a[0] = -32;
        dt = 0.5;
      

Now from the approximations:


        h(t+dt) = h(t) + dt * v(t) \\
        v(t+dt) = v(t) + dt * a(t) \\
        a(t+dt) = -32
      
use the Do statement to compute new values:

        Do[ { h[i]=h[i-1]+dt*v[i-1],
              v[i]=v[i-1]+dt*a[i-1],
              a[i]=-32 },
            {i,1,20}
          ]
      

We can make a plot to see what we have computed:


        hvals = Table[{i*dt, h[i]}, {i,0,20}];

        ListPlot[hvals]
      

Back to TABLE OF CONTENTS.

Dot (Vector Dot Product)

The Dot command allows you to take the dot product of twovectors of the same dimension, to multiply a matrix and a vector, or to multiply two matrices.

To compute the dot product of two vectors, you can use the Dot command, or simply insert a literal "dot" between them:


        Clear [ x, y ]
        x = { 1, 2, 3 }
        y = { 3, 2, 0 }
        result = Dot [ x, y ]
        same_result = x . y
      

The same command can be used to compute the usual matrix-vector product:


        Clear [ A, x ]
        A = { { 1, 2, 3 },
              { 0, 1, 0 },
              { 2, 2, 2 } }
        x = { 1, 2, 3 }
        result = Dot [ A, x ]
        same_result = A . x
      

We can also multiply two matrices:


        Clear [ A, x ]
        A = { { 1, 2, 3 },
              { 0, 1, 0 },
              { 2, 2, 2 } }
        B = { { 1, 2, 3 },
              {},
              {} }
        result = Dot [ A, B ]
        same_result = A . B
      

Back to TABLE OF CONTENTS.

DSolve

The DSolve command solves a differential equation, using exact techniques.

DSolve requires you to specify the following information:

For a simple example, let's solve


        dy/dx = 2 y/x
      
which has the solution y=C x^2, where C is an arbitrary constant.

You specify the differential equation with a double equal sign:


        Clear[x,y]

        solution = DSolve[ y'[x]==2*y[x]/x, y[x], x ] 
      
The answer you are returned should have the form

        {{ y[x] -> x^2 C[1] }}
      
which is Mathematica's way of expressing the answer.

Frequently, a differential equation includes an initial condition. For our example, we might want to specify that


        y(1) = 1
      
in which case DSolve has two equations to satisfy:

        solution = DSolve[ { y'[x]==2*y[x]/x,  y[1]==1 }, y[x], x] 
      

We have written the equations in explicit form, but DSolve will tolerate more general formats; it will also allow us to use second derivatives. If convenient, we might want to use t as our independent parameter. So don't be surprised to see a command like


        DSolve[ { y[t] * y''[t] - y'[t]^2 == 0, y[t], t ] 
      

If you named the output of the DSolve command, then you can plot it, or use it in other formulas, as long as you use the "replacement operator" symbolized by "/.":


        Plot[ y[x] /. solution, {x, 1, 5} ]
      

Of course, sometimes there are no exact techniques to solve a particular equation. in this case, the command will not return any usable information for you. Instead, it will simply repeat the command you gave it. In cases where DSolve cannot solve your equation, you may need to look at the numerical NDSolve command instead.

Back to TABLE OF CONTENTS.

Expand

The Expand command is most useful when you want to force Mathematica to show you an expression in polynomial form, which is currently written as a set of factors, or as a polynomial raised to a power.


        Clear[x]

        Expand[ (x+1) * (x-3)^2 ] 
      

The command Factor can undo the Expand command.

Back to TABLE OF CONTENTS.

Factor

The Factor command takes a polynomial expression and tries to write it as a product of factors. This is similar to replacing 12 by 2 * 2 * 3.


        Clear[formula, x]

        formula = 4*x^5 + 8*x^4 - 3*x^3 - 9*x^2
 
        Factor[formula]
      

When applied to a polynomial fraction, the Factor command tries to factor the top and bottom:


        Clear[formula, x]

        formula = (x^3 - 3 x^2 + 4 ) / ( x^2 - x - 6 )
 
        Factor[formula]
      

The command Expand can undo the Factor command.

Back to TABLE OF CONTENTS.

FindRoot

The FindRoot command tries to find one value for a variable that will make an equation true. The command uses approximate techniques, so the answer is always a number, and it is not exact. The command requires that you supply a starting point, or guess, for the root, and the command may fail if the starting point is not good enough.

When you specify the equation to be solved, you must use the double equal sign.


        Clear[x]

        FindRoot[ x^2 == 7, {x, -2.0} ]
      

FindRoot can find roots for problems that the commands NSolve and Solve can't handle.

Don't forget, though, that FindRoot can only find at most one root when it is called, no matter how many roots there actually are. For this next problem, there are roots at 2 and 4, but we'll only hear about one of them:


        FindRoot[ 2^x == x^2, {x, 3} ]
      

Warning: If the variable you are solving for already has been assigned a value through an equals sign, then the output of FindRoot will be garbled.


        x = 17;

        FindRoot[ x^2 == 4, {x, 3} ]
      
The problem here is that Mathematica believes that x is another name for 17, so it looks like we're asking for solutions of

        289 == 4
      
and believe me, there aren't any! In this case, you should use the command Clear to "free up" the variable x.

The FindRoot command has an output value, but it's not the root, but rather one (usually) or several replacement rules, which would make the equation true if applied. For instance, the output of the command


        FindRoot[ x^2 == 4, {x, 3} ]
      
would be

        { x -> 2 }
      
If you actually wanted to use the computed value, you might use the replacement operator to set the variable to its value, and copy it elsewhere as needed:

        rule = FindRoot[ x^2 == 7, {x, 3} ]
        value = x /. rule
      

The output of the FindRoot command is a numeric estimate of the root, which is typically displayed with just 6 digits of accuracy. If you want to force Mathematica to try harder, you can specify a greater WorkingPrecision:


        FindRoot[ x^2 == 7, {x, 3}, WorkingPrecision->20 ]
      

Back to TABLE OF CONTENTS.

Fit

The Fit command can be used to approximate a set of data with a line...or a parabola or other polynomial if you choose. This process is sometimes called least squares approximation.

In order to use the command, you must have two lists of data, which you can think of as your x and y values. For instance, we might have the population of a city tabulated every ten years:


        year = { 1900,   1910,  1920,  1930,  1940,  1950 }
        pop  = { 10000, 11900, 13400, 17500, 18400, 20300 }
      
To find the formula of a line that approximates this data, we need to make a table of our data, and then fit the data as a line:

        data = Table [ { year[[i]], pop[[i]] }, { i, 1, 6 } ]

        Fit [ data, { 1, year }, year ]
      

The argument { 1, year } is actually how we tell Mathematica that we want a line; we're telling it to come up with a formula of the form:


        pop[year] = a * 1 + b * year
      

The output of the Fit command is actually a formula. If you plan to use this formula, or plot it, you'll need to specify a name for the output of the command, using the form that defines a function:


        pop_line [ year_ ] := Fit [ data, { 1, year }, year ]
      
Now, to ask what the linear estimate of the population is for 1966, you just type

        pop_line[1966]
      

Sometimes a straight line isn't good enough. If we want a parabolic fit, our command would be:


        Fit [ data, { 1, year, year^2 }, year ]
      

When using polynomials, it is not necessary to include all the powers. For instance, it might make sense to approximate a function using only odd powers of x, and this can easily be done:


        Fit [ data, { x, x^3, x^5, x^7 }, x ]
      

And it's not necessary to use polynomials. You could use trigonometric functions, or exponentials or other sets of functions:


        Fit [ data, { Sin[x], Sin[2x], Sin[3x] }, x ]
      

Back to TABLE OF CONTENTS.

Flatten

The Flatten command is used when you're working with a list, but somehow, you've got extra curly brackets running around. The Flatten command ignores all the curly brackets in a complicated list, extracting just the numbers, and slaps a curly bracket on either end.

Suppose, for instance, that you've computed an interpolating function solution to an ODE using NDSolve, and now you'd like to plot it. If you issue the command:


        ylist = Table [ y[t] ./ solution, { t, 0, 10, 0.1 } ]
      
you'll get output like

        ylist = { {0.0}, {0.123}, {0,146}, {0.236}, ... {2.342} }
      
which won't work with ListPlot because of all those internal curly brackets. But if you just change the command to

        ylist = Flatten [ Table [ y[t] ./ solution, { t, 0, 10, 0.1 } ] ]
      
you'll get output like

        ylist = { 0.0, 0.123, 0,146, 0.236, ... 2.342 }
      
and ListPlot will be happy.

Similarly, the Flatten command can be used to convert a matrix into a vector of its entries, listed one row after the next.

Back to TABLE OF CONTENTS.

If

The If command is a feature that allows you to make decisions or choose a particular course of action in a program. The form of the If command is:


        If [ condition, true_expression, false_expression ]
      
The condition is a logical expression, which most commonly compares two numerical values. If the logical expression is true, then the true expression is evaluated, and if the logical expression is false, the false expression is carried out. The true and false "expressions" can be a value or a command,

In this example, we want to compute the inverse of a number, or print a message:


        Clear [ x, x_inverse ]

        If [ x == 0, Print ["Error!  X is zero!], x_inverse = 1 / x ]
      

Of course, it may be the case that, where we have written true expression, you actually want to place more than one statement. For instance, in the inverse case, perhaps we want to print a message and set the value of x_inverse to infinity. This is easy to do: simply group the statements inside a set of curly brackets, and they are the same as one statement:


        Clear [ x, x_inverse ]

        If [ x == 0, { Print ["Error!  X is zero!], x_inverse = Infinity }, 
             x_inverse = 1 / x ]
      

As in the C programming language, the If statement takes on the value of the true or false expression, and so that value can be assigned to a variable:


        Clear [ x, x_inverse ]
  
        xabs = If [ x <= 0, -x, x ]
      

It is possible for the condition or logical expression to be neither true nor false, particularly if the variables in the expression have not been assigned values. In this case, the expression is considered to have the value "unknown". The If statement will not evaluate either expression, and its value will also be "unknown". If you anticipate such cases occurring, you can use a more elaborate version of the If statement:


        If [ condition, true_expression, false_expression, unknown_expression ]
      

Back to TABLE OF CONTENTS.

Infinite Series

An infinite series is an expression that represents the sum of an infinite sequence of quantities. There is a standard mathematical notation for infinite series. For instance, to represent the infinite sum S of the quantities 1, 1/2, 1/4, 1/8, ..., we would write


        S = Sum { i = 1 to Infinity } 1/2^i.
      

Using limits, it may be possible to assign a value to an infinite series. We do this by considering the behavior of partial sums in the limit. For instance, let us write Sn to represent the sum of the first n terms of the series.

Certainly, for any n, we can compute this quantity. The first few values of Sn are 1, 1.5, 1.75, 1.875, ... and we might guess (correctly) that the value never reaches 2, but can be made as close to 2 as we want by choosing n large enough. In other words,


        Limit ( n -> Infinity ) Sn = 2.
      

In some cases, the limit is infinite, and we say that the series diverges to infinity. In other cases, there is no limit at all, and the series cannot be assigned any value.

Therefore, you might think that one way to analyze a series with Mathematica is to define the sequence of partial sums, and then apply the Limit command. For our simple series above, here is how we could do this:


        Clear[n, partial]

        partial[n_] := Sum[ 1/2^i, {i,1,n} ]

        Limit[ partial[n], n->Infinity}
      

Such an answer is useless. Mathematica is telling us it doesn't know how to handle this extremely simple problem. We can try another approach: simply use the Sum command with an infinite upper limit:


        Sum[ (1/2)^i, {i,1,Infinity} ]
      

This seems to be getting us nowhere! Actually, however, Mathematica has computed the answer, but we have to force it out with the command N (Numeric Value)!


        N[ Sum[ (1/2)^i, {i,1,Infinity} ] ]
      

A useful tool for sequences is the Ratio Test, which considers the limit of the absolute value of the ratio of terms n+1 and n. If this limit is less than 1, then the infinite series is guaranteed to have a (finite) limit. If the limit is greater than 1, then the infinite series diverges, while if the limit is exactly 1, the test is inconclusive. We can make this test easily:


        term[n_] := 1/2^n

        Limit[ term[n+1] / term[n], n->Infinity}
      

You may also want to refer to the discussion of Sequences.

Back to TABLE OF CONTENTS.

Integrate

The Integrate command can be used to compute the indefinite integral of a function:


        Clear[c,x]

        Integrate[ x^2, x] 
      

Notice that Mathematica does not tack on a symbolic constant like C to the answer. If your instructor is impressed by that sort of thing, you can tack on the old constant to your answer like so:


        Integrate[ Sin[x], x] + C
      
which works as long as C hasn't been given any other meaning yet.

The Integrate command can also be used to compute the definite integral. In this case, you must enclose the variable of integration and the limits of integration in curly brackets.


        Integrate[ x^2, {x,0,3} ]
      

In some cases, the Integrate command can compute answers in which the lower limit is minus Infinity or the upper limit is Infinity:


        Integrate[ 1/x^3, {x,1,Infinity} ]
      

Integrate can easily handle definite integrals involving symbolic limits, which is useful when considering an improper integral. (Of course, Mathematica can handle improper integrals easily, but we may want to see the steps ourselves.) For instance, here is one way we could compute the value of the improper integral of 1/x^2 from 1 to Infinity:


        Integrate[ 1/x^2, {x,1,b}]

        Limit[ 1 - 1/b, b->Infinity}
      

If Mathematica does not know an exact antiderivative of the function, then it will simply reprint the input you typed. If you don't think Mathematica is going to give you a useful answer, and you need a definite integral (not an indefinite one!) with numeric (not symbolic!) limits, then you can try using the command NIntegrate instead.

Double Integrals

It's easy to do a double integral! You simply iterate the Integrate command properly. Let's make things a little more interesting by integrating over the unit triangle. Here's an example:


        Integrate[ 
          Integrate[ Log[x+y], { y, 0, 1-x } ],
                                  { x, 0, 1 } ]
      

Back to TABLE OF CONTENTS.

Limit

The Limit command is used to compute the limit of an dependent variable or expression as some independent variable approaches a special value.


        Clear[f, h, x]

        f[x_] := x^3 

        Limit[ (f[x+h]-f[x])/h, h->0] 
      

Apparently, Mathematica only computes one-sided limits, and by default, computes them "from the right". Mathematically, the function 1/x does not have a limit at 0; we can't even say its limit is infinity, because approaching zero from below, the function goes to negative infinity. But if you ask Mathematica, you get the answer Infinity, because it allows infinity as a value for a limit, and looks for the limit only from the right.

To compute a left-hand limit, you need to specify the Direction:


        Clear[f,x]

       f[x_] := 1/x

       Limit [ f[x], x->0 ] 
         (Answer is Infinity)
       Limit [ f[x], x->0, Direction -> 1 ]
         (Answer is -Infinity)
      

Now if you really, really want a limit, you must compute it from both directions, which Mathematica will not do for you automatically. Only if both limits exist and are equal can we correctly say that we know the value of the limit.

Mathematica seek limits as a variable goes to a particular numerical value, but it can also handle cases where the independent variable goes to positive or negative Infinity:


        Limit[ (7*x+1)/x, x->Infinity] 
      

For instance, to compute the value of an improper integral, you might let the upper limit be t, and then look at the limiting value as t goes to infinity:


        Limit [ Integrate [ 1/x^3, { x, 1, t } ], t->Infinity ]
      

By the way, Mathematica can actually handle the commands Integrate and Sum with an upper limit of Infinity.


        Integrate [ 1/x^3, { x, 1, Infinity } ]
      
The result should be the same as applying the Limit command in the appropriate way.

Back to TABLE OF CONTENTS.

Lists of Data

In many cases, you will want to set up or reference data in a list. In Mathematica, the simplest kind of list corresponds to a "vector", and is simply a list of number or symbolic values, separated by commas and enclosed in curly brackets:


        Clear[v]

        v = { 1, Sin[Pi/5] }
      

Individual entries of a list may then be accessed by using double square brackets. You can use the command ListPlot to plot such data.


        Clear[datax]
        datax = { 1, 2, 5, 8, 14, 12, 6, 3 }

        datax[[3]]
      

Warning: although you can "read" a list value using the double square bracket notation, you can't change the value this way. That is, it is not legal to write:


        datax[[3]] = 7
      
even though this might seem quite logical. Instead, you must use the Replace command discussed below!

In some cases, it's more convenient to reference list items by position. The First and Last commands return the first and last entries of a given list:


        Clear[ beginning, datax, end ]
        datax = { 1, 2, 5, 8, 14, 12, 6, 3 }
        beginning = First[datax]
        end = Last[datax]
      

Mathematica has several commands that allow you to modify a list:

Thus, once we define a list:


        Clear[datax]
        datax = { 1, 2, 5, 8, 14, 12, 6, 3 }
      
we can add a value of 17 to the end by:

        datax = Append [ datax, 17 ]
      
We can change the third entry from 5 to 50 by:

        datax = Replace [ datax, 50, 3 ]
      

Back to TABLE OF CONTENTS.

Lists (Two Dimensional)

What about a two dimensional array or matrix? Mathematica thinks of such quantities as simply a list of lists. Thus, a two dimensional array is again a list of quantities separated by commas and enclosed in curly brackets. What makes it special is that the quantities themselves are lists, namely, the rows of the matrix. If we call our list chart, here is how we might set it up:


        Clear[chart]
        chart = { {11, 12, 13, 14}, 
                  {21, 22, 23, 24},
                  {31, 32, 33, 34} }
      

Now we can refer to row 2 of chart as:


        chart[[2]]
      
or to the entry in row 2, column 3 as:

        chart[[2,3]]
      

However, there is not an easy way to reference a column of data. The best way uses the command Table.

Back to TABLE OF CONTENTS.

Logical Expression

Mathematica includes some operators that allow you to test whether certain conditions are true or false (or undefined). Using these operators, you can form logical expressions. A logical expression is required, for instance, in the If statement.

The simplest logical expressions involve numerical comparisons, and have the following forms:

In the above examples, if x and y have been assigned numerical values, then each expression is guaranteed to be true or false. But if one or both of the variables have not been assigned a value, then the logical expression is neither true nor false!

Logical expressions can be combined or negated. If A and B are logical expressions, then

Back to TABLE OF CONTENTS.

N (Numeric Value)

The N command is used to turn a symbolic or exact number or result into a decimal value.


        Clear[x]

        N[Pi]

        Integrate[Sin[x],{x,0,1}]

        N[Integrate[Sin[x],{x,0,1}]]
      

You can request more decimal places of accuracy:


        N[Sqrt[2],20]

        N[Pi,100]
      

The output of many Mathematica commands is one or more symbolic values. You can simply "wrap" the N command around such a command, to convert the results to a numerical value:


        N[ Solve[ x^3-3*x^2-5*x+15 == 0, x ] ]
      

Back to TABLE OF CONTENTS.

NDSolve

The NDSolve command is similar to the DSolve command in that it is used to solve one or more differential equations with initial conditions. However, instead of seeking an exact solution, or formula, it numerically estimates the solution at a series of points, and returns an interpolating function.

There are many differential equations for which no exact solution is known, and for which DSolve will be unable to return any useful information. For such problems, NDSolve can usually be applied to give some insight into the shape of the solution.

The interpolating function returned by NDSolve is an estimate for the behavior of the function. It's not exactly a formula, but if you name the output of the command, you can use it to evaluate the estimated solution at a point, or to plot it over an interval.

The format of the NDSolve command is:

        name = NDSolve[  {  
                       Differential equations, initial conditions}, 
                                y[x], {x, xmin, xmax} ]
      

For example, to solve the problem


        dy/dx = (4-2x) * y 
      
with initial condition:

        y(0) = 1/6
      
over the interval 0 <= x <= 5, we would issue the following commands:

        Clear[solution, x, y]

        solution = NDSolve[ { y'[x] == (4-2*x)*y[x], y[0] == 1/6 }, y[x], 
          {x, 0, 5} ]
      

In order to actually get numbers out of our answer, we have to use the /. substitution operator. For instance, if our function y was defined by a formula in the usual way, we would get the value of y at 1.0 by typing y[1]. Now, our function is not a formula, but an interpolation function whose properties are defined in the variable that we called solution. Therefore, we have to use the following command to evaluate y[1.0]:


        y[1.0] /. solution
      

Similarly, wherever we would normally use a formula like y[x], we instead must use the expression y[x] /. solution. Here, for instance, we make a table of the solution:


        Clear[ xy_table ]
        xy_table = Table[ {x, y[x] /. solution }, {x, 0, 5, 0.5} ];

        TableForm[ xy_table, TableHeadings->{None, {"x","y[x]"} } ]
      

To get a plot of your interpolating function, you could do something like this:


        ylist = Flatten [ Table[ y[x] /. solution, {x, 0, 5, 0.5} ] ];
        ListPlot [ ylist ]
      

Warning: An interpolating function may only be evaluated over a specific range. For our example, we only asked for an approximate solution over the range 0 <= x <= 5. Mathematica will refuse to compute a value of the interpolating function outside this range:


        y[6] /. solution
      

Back to TABLE OF CONTENTS.

Needs

Many useful commands are not in the main part of Mathematica. For instance, there is a command called ConvexHull, which you might want to use some time. But because it's not in the main part of Mathematica, if you simply type the command ConvexHull, two bad things will happen:

This spectacular goofup is because of Mathematica's superior design, of course.

Anyway, whenever you are using a command that is not part of the main portion of Mathematica, you need to make sure that you give enough information so that that particular command can be found and properly loaded. Mathematica keeps its extra commands in packages, and so before you use a command, you just specify what package you will be needing, using the Needs command. Be careful to type in the double quotes and the backward quotes exactly as they appear here!


        Needs["Graphics`Graphics`"]
      

The command << can be used instead of Needs. However, every time it is invoked, the command reads in a new copy of the requested package, and does not wipe out the old copies. Reading the same package can cause memory or logic problems for Mathematica.


        << Graphics`Graphics`
      

Back to TABLE OF CONTENTS.

NIntegrate

The NIntegrate command approximates the definite integral of a function between two limits. Instead of trying to find the indefinite integral, and then using the Fundamental Theorem of Calculus, NIntegrate uses ideas based on Riemann sums to get an approximate value of the integral of many functions for which the command Integrate cannot get the exact value.


        Clear[x]

        NIntegrate [ Sin[x^3], {x,0,1} ]
      

NIntegrate no longer requires finite numerical values for the upper and lower limits of the integral. You can use NIntegrate for integrals with an upper or lower lower bound of Infinity.


        1/(2 Pi) NIntegrate[ Exp[-x^2/2] / (1 + x^2), {x, -Infinity, +Infinity}]
      

You may find it maddening that the result returned by NIntegrate will appear to have just 6 places of decimal accuracy, and it will seem to be impossible to convince Mathematica to print out the further digits that you expect it is hiding from you. Luckily, it is only almost impossible to do this. You can get more digits to appear, but you do so by repeating the calculating with an explicit request for more digits, something like this:


        1/(2 Pi) NIntegrate[ Exp[-x^2/2] / (1 + x^2), {x, -Infinity, +Infinity},
        WorkingPrecision->15, PrecisionGoal->10]
      

Back to TABLE OF CONTENTS.

NSolve

The NSolve command tries to find all the roots of an equation involving polynomials, using approximate methods. A polynomial equation involves a variable x, and various combinations of positive integral powers of x.

The equation to be solved is specified using a double equal sign. The second argument is the name of the variable to be solved for.


        Clear[x]

        NSolve[ x^2 == 7, x]
      

Note that there is no general formula for the exact roots of a polynomial of degree 5 or greater, so the Solve command will be unable to solve many "simple" polynomial problems. But NSolve should be able to approximate all the roots of most polynomial equations. NSolve will fail on equations that are not polynomial. Here is an example:


        NSolve[ x^2 == 2^x, x]
      
This is not a polynomial problem, because the variable x occurs as an exponent. Similarly, if terms like Sin[x] or Sqrt[x] or 1/x occur, you don't have a polynomial problem, and you can't use NSolve. In such cases, you should move on to the more general FindRoot command!

Back to TABLE OF CONTENTS.

NSum

NSum numerically estimates the value of an infinite sum.

To estimate the sum of the terms 1/2^n, the command would be


        Clear[n]

        NSum[ 1/(2^n), {n,1,Infinity} ]
      

Since NSum only uses numerical techniques, it cannot sum symbolic quantities, and the answers it produces may be slightly or greatly inaccurate. For instance, the actual sum of the terms 1/n is infinite, but here is what NSum tells us:


        NSum[ 1/n, {n,1,Infinity} ]
      

If you are summing symbolic quantities, or need an exact answer, you should refer to the command Sum.

Back to TABLE OF CONTENTS.

Plot and D Don't Mix

If you have defined a function f[x_], and you want to plot its first derivative, then the proper way to do this is to use the "prime" or "single quote" symbol in the command Plot:


        Clear[f, x]

        f[x_] := Sin[x]

        Plot[ f'[x], {x,0,Pi} ]
      

You cannot use D[f[x],x] in the Plot command, even though it means the same thing (to us) as f'[x]! This is because the Plot command would see the variable x used twice, once as a symbolic argument, and once as the range of plotting. So the following command won't work:


        Plot[ D[f[x],x], {x,0,Pi} ]
      

You may want to refer to the commands D (Differentiate), or Plot.

Back to TABLE OF CONTENTS.

Prime

The command Prime[n] produces the n-th prime number. This command will operate fairly quickly for n as large as 100,000,000.

Here's the first prime number:


        Prime[1]
      
and here's one way to print out the first 10 primes:

        Do [ {
          Print ["n=", n, " Prime[n]= ",Prime[n] ] },
          {n, 1, 10} ]
      

Back to TABLE OF CONTENTS.

Print

If you want to see the value of a variable, you can simply type its name. For more complicated output, the Print command can help you display output lines that include values and text.

For example, to neatly print the value of pi, you might write:


        Print[ "The value of Pi to 20 places is ",N[Pi,20] ]
      

For another example of the Print command, see the Do command.

Back to TABLE OF CONTENTS.

Random

The Random function returns a "random" number between 0 and 1. This function can be used to set up a random list or table of data, to define a matrix with random entries, or to simulate a process that is described probabilistically.

In this example, we flip a coin 100 times, and count the heads and tails. We use the If command to decide whether the random number represents a head or a tail, and to increment the appropriate quantity:


      Clear [ flip, heads, i, tails ]

      heads = 0;
      tails = 0;

      Do [ {
        flip = Random[];,
        If [ flip < 0.5, tails = tails + 1, heads = heads + 1 ]
        }, 
        { i, 1, 100 } ]

      Print [ "Number of heads was ", heads ]
      Print [ "Number of tails was ", tails ]
      

Here is a simple example which uses the Table command to define a table of 4 rows and 5 columns with random entries:


        Clear [ A ]

        A = Table [ Random[], {4}, {5} ] // TableForm
      

Back to TABLE OF CONTENTS.

Sequences

We can think of a sequence as an endless list of numbers, whose values are determined by some rule. Each number in the sequence is called a term of the sequence. We think of the terms as being numbered, starting with term 1 or sometimes with term 0.


        Clear{f,fib,n,values}
      

Some sequences can be defined by writing a formula for the n-th term. In such a case, any particular term of the sequence can be found simply by evaluating the formula. For instance, if the n-th term is (2 n +1)/n, then we can symbolize the general term with a formula, and find the value of, say, the 10-th term by evaluating the function there:


        f[n_] := (2*n+1) / n

        f[10]
      

We can use Mathematica commands like Table or even Plot:


        values = Table[ {n, f[n]}, {n,1,5} ];

        TableForm[values]

        Plot[ {0, f[n]}, {n,1,5} ]
      

It's usually easy for Mathematica to check the limit of the sequence, or even to differentiate it, when using L'Hopital's rule.


        Limit[ f[n], n->Infinity]
      

In some cases, however, we don't know a formula for each term. Instead, we may know a rule for making the next value of the sequence from the previous values. A sequence defined in this way is called a recursive sequence. For instance, the Fibonacci sequence is defined as follows: the first two terms are 0 and 1, and each following term is the sum of the two previous ones, so the sequence begins 0, 1, 1, 2, 3, 5, 8, 11, ....

How can we get Mathematica to handle this case? We have to use a special form of the function definition, in which we specify the starting values, and the rule for getting the next one:


        fib[0] = 0;
        fib[1] = 1;

        fib[n_] := fib[n] = fib[n-2] + fib[n-1]
      

Notice that we counted the first term as number 0, rather than 1. That's up to us. Notice also the strange form of the functional definition. The expression fib[n] is not actually necessary; it is there to make the computations faster. It tells Mathematica that, whenever it computes a specific value of the Fibonacci sequence, it should "remember" it, so that it can be used in other computations.

The other thing to note about this sort of definition is that we can't use a Plot command to display the function, since it will only be defined for integer values. Instead, we must use the command Table to gather up the values we want, and then display them with the command ListPlot.


        values = Table[ {n, fib[n]}, {n,0,5} ];

        ListPlot[ values, PlotJoined->True]
      

Another problem with recursive sequences is that we can't use the Limit command with them. If you actually entered the following Mathematica command, you might wait several minutes, with no response, before having to go up to the Action menu and selecting Abort Calculation to halt it:


        Limit[ fib[n], n->Infinity]
      

One common source of sequences is in the study of Infinite Series. We try to understand such quantities by considering the limit of the sequence of partial sums.

Back to TABLE OF CONTENTS.

Series

The Series command produces the beginning terms of a power series for a given function. For instance, let us suppose we want the series for ln(x) around the point x=1, up to the term involving fourth powers:


        Clear[approx,f,result,t,x]

        f[x_] :=  Log[x]

        Series[ f[x], {x, 1, 4} ]
      

The error term O(x-1)5 is an expression that tells us how our approximate curve will differ from the true curve as we move away from 1. Now we're just interested in the series function itself, without this error term. We could simply type it in again, but we don't have to. The Normal command exists just to chop off the error term. For future use, we will also name this quantity:


        result = Normal[ Series[ f[x], {x, 1, 4} ]  ]
      

Note that we could probably have used the simpler command Normal[\%].

There are many interesting things to do with a series approximation, but we will need to have Mathematica treat it as a function first. This is surprisingly difficult to do. We'd like to think of it as a function of x, but unfortunately, the symbol x was used to define the function in the first place. We just have to figure out a way to make a new version of the function with a different symbolic variable:


        approx[t_] := result /. x-> t
      

This command essentially says that once you've gotten the power series for ln(x), replace x by t in the formula. This is only so that we can define the function properly. Once that's done, we can use any variable name as an argument of approx. Once we have set up or function, we can plot it or make tables.


        data = Table[ {x, f[x], approx[x], f[x]-approx[x]},{x,0.5,5,0.5} ];

        TableForm[data]
      

A plot of ln(x) versus the approximation shows good agreement near the point x=1, but the error increases rapidly after x=2.


        Plot[ {f[x], approx[x]}, {x, 0, 3},
          PlotStyle->{RGBColor[1,0,0], RGBColor[0,0,1]}]
      

Back to TABLE OF CONTENTS.

Simple Functions

Many Mathematica commands, such as D (Differentiate), Integrate, and Plot, expect to receive a function to work on. The variable that the function depends on is very important, and it's best to define a function of a variable in a way that allows Mathematica to understand what's going on:


        Clear[f, x]

        f[x_] := 10*x^2+1
      

The underline is only used on the left hand side, after the name of the independent variable, and you must also be sure to use the "colon-equals" sign as part of the function definition. If you want to pass the function to a Mathematica command, you specify it as f[x].


        Clear[f, x]

        f[x_] := 10*x^2+1

        D[ f[x], x]
      

You can easily evaluate the function by replacing its argument by a number.


        Clear[f, x]

        f[x_] := 10*x^2+1

        f[3] 
      

Be careful, though. If you plan to use the expression f[x] in a Mathematica command, then x should not have been assigned a particular value. You should not issue a command like x=1, for instance, because then Mathematica will become confused.


        Clear[f, x]

        x = 3

        f[x_] := 10*x^2+1

        f[x]

        Integrate[ f[x], x]
      

On the one hand, Mathematica thinks x is the number 1, and on the other hand, it will think x is an argument of a function, and can have any value. If you think you're having a problem like this, use the command Clear to get rid of it!


        Clear[f, x]

        x = 3

        Clear[x]

        f[x_] := 10*x^2+1
 
        Integrate[ f[x], x]
      

To see how to make a function that carries out several steps, uses iteration, or uses temporary variables, refer to Advanced Functions.

Back to TABLE OF CONTENTS.

Simplify

Mathematica can simplify many polynomial or trigonometric expressions, but usually you must explicitly request it to do so, using the Simplify command. For instance, the polynomial fraction


        (x^2-2x-3) / (x+1)
      
can be simplified:

        Clear[x]

        (x^2-2*x-3) / (x+1)

        Simplify[ (x^2-2*x-3)/(x+1) ]
      

Another time when Simplify is useful is when verifying that one function is the inverse of another:


        Clear[f, g, x]

        f[x_] := (x+2)/x
        g[x_] :=  2/(x-1)

        Simplify[ g[ f[x] ] ]
        Simplify[ f[ g[x] ] ]
      

You might also be interested in the commands Apart, Expand, Factor, or the Together.

Back to TABLE OF CONTENTS.

Solve

The Solve command can be used to seek values of a variable which make an algebraic equation exactly true. The command will try to find all possible solutions. When you describe the equation to the command, you must use two equal signs! (Technically, this is because you are giving a logical expression, and asking for values that make it true. In some cases, Solve will return an answer in symbolic form, since it is computing exact values.


        Clear[x, y]

        Solve[ x^2 == 7, x] 
      

In some cases, you may want to use the N command to immediately convert the output of Solve to decimal values:


        N[Solve[x^2 == 7, x] ]
      

Solve can handle equations in which extra variables appear, even if those variables have not been assigned a value.


        Clear[x, y]

        Solve[ 2*x+y == 1, x] 
      

Solve can solve several equations in several unknowns:


        Solve[ {2 x + 3 y == 8, 
                  x +   y == 3}, {x, y} ]
      

Solve can handle some equations that include trigonometric functions:


        Clear[x]

        Solve[ y == 12 + 0.6*Sin[(t-80)/3], t]
      

Solve should be able to treat any polynomial equation of order 4 or less. But higher order equations can make Solve fail. For instance, if Solve fails, and returns a message that begins with the words "ToRules", it's telling you that it can't find the exact solution, but does have a numerical estimate, which you can get by typing N[\%]:


        Clear[x]

        Solve[  x^5+2*x+1==0, x]

        N[%]
      

And here is a transcendental equation that Solve cannot handle. (The problem is the term 2x:


        Clear[x]

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

If Solve can't handle your equation, you may need to try the NSolve command, which uses approximate techniques and seeks all roots, or FindRoot, which uses approximate techniques and seeks just one root.

Back to TABLE OF CONTENTS.

Special Constants

There are several special constants that Mathematica names:

Back to TABLE OF CONTENTS.

Special Functions

Mathematica has many mathematical functions, including:

Back to TABLE OF CONTENTS.

Sum

The Sum command computes the sum of a set of numbers. One way to specify the set of numbers is as a formula:


        Clear[a, b, delx, f, i, n, x]

        Sum[ 2*i-1, {i, 1, 10} ]
      

You can also specify an increment, which tells how the index variable is increased from the lower limit to the upper limit. For instance, you could also add up the odd numbers between 1 and 19 by typing


        Sum[ i, {i, 1, 19, 2}]
      

The counter variable does not have to be an integer. To do a left hand Riemann sum, for instance, you could try a formula like this:


        f[x_] := x+1
        a = 0;
        b = 2;
        n = 8;
        delx = (b-a)/n;

        N[ Sum[ f[x]*delx, {x, a, b-delx, delx} ] ]
      

The upper limit of the Sum command can be Infinity.


        Sum[ 1/2^n, {n,1,Infinity} ]
      

Sometimes, the Sum command may compute a useful answer for an infinite sum, but does not report it to you. When this happens, you may be able to retrieve a numerical result by using the command N (Numeric Value):


        N[ Sum[ 1/2^n, {n,1,Infinity} ] ]
      

If the Sum command does not perform satisfactorily, and you can accept a numerical approximation, you may be interested in the command NSum.

Back to TABLE OF CONTENTS.

Table

The Table command allows you to set up and store a table of data. Usually, you want to use a semicolon at the end of the Table command to suppress its output.

When you're ready to print out your table data, the command TableForm prints out the table in a neat format, with optional row and column labels:


        Clear[col2, fibonacci, i, row1, row2, row5, squares]

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

        TableForm[squares,
          TableHeadings->{None, {"Number", "Square"} } ] 
      

A table is not just something to be printed out. It is also an array of data, usually two dimensional. Any single entry of the table can be accessed by specifying its row and column numbers, within double square brackets:


        squares[[7,2]]
      

Similarly, any row of the table can be accessed by specifying just the row number. The result will be a list:


        row5 = squares[[5]]
      

Getting a column of the table into a list is a little trickier. We'll actually use the Table command to do it!


        col2 = Table[ squares[[i,2]], {i,1,9} ]
      

You can build a table, one row at a time, from a collection of lists:


        row1 = {1, 2, 3, 4, 5, 6}
        row2 = {1, 1, 2, 3, 5, 8}

        fibonacci = {row1, row2}

        TableForm[fibonacci,
          TableHeadings->{{"N", "Fibonacci Number"}, None} ]
      

Back to TABLE OF CONTENTS.

TableForm

The TableForm command prints a table in a neat format, by rows and columns. The table will usually have been set up by the command Table.

In the simplest use, we immediately follow a Table command by a TableForm command, whose argument is simply \%:


        Clear[i, matrix]

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

        TableForm[%] 
      

Sometimes, you have two or three lists, and you want to print them as columns of a table:


        year =       { 1900, 1920, 1940, 1960, 1980, 2000 }
        population = {  100,  103,  109,  112,  113,  117 }
        Table[ { year[[i]], population[[i]] }, { i, 1, 6 } ]
        TableForm[%]
      

If the data is already a named matrix or table, then you can print it right away:


        matrix = { {11, 12, 13}, {21, 22, 23}, {31, 32, 33} }
        TableForm[matrix]
      

The TableForm command can also be applied to the output of a command by appending it to the command:


        Clear[i, matrix]

        Table[ {i, i^2, i^3}, {i,1,10}] // TableForm
      

The rows and columns may be labeled by specifying the TableHeadings option. The form of the option is:


        TableHeadings->{ 
          {"row 1 label",    "row 2 label",    ..., "last row label"},
          {"column 1 label", "column 2 label", ..., "last column label"} }
      

If there are to be no row labels, then the entire list of row labels is replaced by the word None; the same holds if there will be no column labels:


        TableForm[ matrix, TableHeadings->{ 
          {"Row 1", "Second Row", "Last One"},
          {"Column 1", "Column 2", "Column 3"} } ]

        TableForm[ matrix, TableHeadings->{ 
          None, {"Column 1", "Column 2", "Column 3"} } ]

        TableForm[ matrix, TableHeadings->{ 
          {"Row 1", "Second Row", "Last One"}, None } ]
      

Warning: If your column labels are too long to fit on one line, then TableForm will produce ugly output, by just continuing the labels (and the data beneath them) onto the next line.

Back to TABLE OF CONTENTS.

Together

The Together command can be used to take several polynomials and polynomial fractions and join them into a single polynomial fraction with a common denominator. This is similar to the operation of converting 2/3 + 1/4 + 3 into 47/12.


        Clear[stuff, x]

        stuff = x^2 + 1 + (x-3) / (x^2 -3*x + 4) 
        Together[stuff] 
      

The command Apart can undo the Together command.

Back to TABLE OF CONTENTS.

Vectors

A vector in Mathematica is simply a list.

A list is a set of values, separated by commas, and enclosed in curly brackets:


        x = { 1, 2, 3 }
        y = { 0, -2, 3 }
      
A specific entry of a list can be accessed by using double square brackets to indicate its position:

        x[[2]] = 3
        total = y[[1]] + y[[2]] + y[[3]]
      

Mathematica doesn't make a distinction between row and column vectors. If you really want a column vector, you need to set it up as a matrix of n rows and 1 column:


        w = { {1}, {2}, {3} }
      

Arithmetic operations on vectors include:

Back to TABLE OF CONTENTS.

You can return to the HTML web page.


Last revised on 07 February 2014.