A Brief Introduction to
Mathematica

by Duane Storti

Note : You can find an alternate screencast introduction to Mathematica online at < http://url.wolfram.com/qc9Pje/ >.

What is Mathematica?

In "The Mathematica Book" by Stephen Wolfram, Mathematica is described as "the world's only fully integrated environment for technical computing." While there are certainly other software providers who would argue about the "only", there is no doubt that Mathematica provides a unified environment that supports many of the kinds of computation that arise in engineering: symbolic manipulation, numerical computation, and graphic visualization, etc. In addition, Mathematica provides capabilities for editing and formatting (this document was prepared using Mathematica), playing sounds, and programming your own custom features.

Getting Started: How do I use it?

To get started using Mathematica, log on (or establish a remote connection as described in the Remote Computing document) and start up the application. If there is a Mathematica icon on the desktop, just double-click on it. Otherwise, click on the START button at the lower left hand corner of the screen then drag up to programs until another menu pops up. Drag to the Mathematica folder, and when it opens, click on Mathematica 6 to launch the program.

Mathematica provides for several levels of user interaction. New users often view Mathematica as an interactive super-calculator. While batch mode is available, you are more likely to interact with Mathematica through the "Notebook" interface (You are looking at a notebook right now! Notebooks provide a convenient way to communicate with the Mathematica kernel where the actual computations are performed.) in which items are organized into various types of cells (indicated by the blue brackets along the right edge of the notebook).

Typically when you start the program, an empty notebook will pop open for you to work in. If there is no open notebook, or if you need an extra one to work in, select NEW from the FILE menu at the upper left corner of the screen to create a new notebook.

Once you have an open notebook to work in, a  veritable plethora of built-in functions can be accessed by typing the function name and inputs (with appropriate syntax as discussed below) into an input cell followed by <SHIFT-ENTER>. Mathematica then evaluates the function and prints out the result immediately below in an output cell. The results of previous calculations can be saved and accessed later to build up more complicated calculations as indicated below.

To illustrate a basic numeric calculation, move the mouse over this paragraph (which appears in a text cell identified by the horizontal tick mark near the top of the blue cell bracket) then move down until the cursor changes to a horizontal I-beam. Click the left mouse button to create a cell boundary (indicated by a solid horizontal line), and type "2 + 2" or some other numerical operation. What you type will appear in an input cell (denoted by the diagonal line at the top of the cell bracket, or check the Format-Style submenu). Evaluate the contents of your input cell by pressing <SHIFT-ENTER> (i.e. the SHIFT and ENTER keys pressed simultaneously), and the results of the evaluation will appear in a output cell (denoted by a diagonal line above the horizontal tick) just below the input cell. Try entering and evaluating a couple numerical expressions. What happens when you double click on the outer cell bracket that groups the output and input? How does the bracket change its appearance? What happens if you double-click it again?

The cells  below illustrate symbolic calculation and graphics. Click in the cell and evaluate (using <SHIFT-ENTER>) to see the corresponding output.

Expand[(x+y)^4]  (* This shows how to put a comment in an input cell *)

Factor[%] (* Sample algebraic computation."%" is shorthand for "the previous result". *)

N[π, 100] (* Sample numeric computation *)

D[x^3, x] (* Sample calculus operation *)

Plot[Sin[π t], {t,0, 4}] (* Sample 2D plot *)

Plot3D[x^2+y^2,{x,-3,3},{y,-3,3}] (* Sample 3D plot *)

Note that all built-in functions and constants start with an upper case letter or $ (so when you make up names for things you create, just start with lower case and you will never have a name collision with something built-in).

Arguments to functions appear in square brackets [ ] following the function name. (We'll discuss later that EVERYTHING in Mathematica has an internal representation of this form.)

% is a special symbol which refers to the output of the previous computation.

Note that putting a semi-colon at the end of the line supresses the output. (Try it!)

Saving your work

You can save your work during your session by simply saving your notebook. However, the machines in the ME department computing labs are not designed for saving personal files. Use FTP or Pine e-mail to transfer your files or send them as e-mail attachments to locations where you have file storage capability.

Getting Help

There are so many built-in functions in Mathematica that it can be mind-boggling. The listing of the built-in functions requires 350 pages and the index by itself is 80 pages long. How can you possibly expect to find the functions you need for your intended purpose? Luckily, there are extensive on-line help facilities, and you should plan on using them regularly. (Learning how to use the help facilities is one of the most important things you can learn in your first Mathematica session. A very efficient approach to getting results involves finding a closely related example in the documentation - s you know that the syntax is correct - and editing as needed for the problem you are working on.)

When you first start Mathematica, you may also see a Startup Palette in addition to the menus and notebook. The Startup Palette includes links to "First Five Minutes with Mathematica" (which you may find as a useful review of the sme topics discussed in this notebook), the Documentation Center, and the Demonstrations Project (which may become more relevant as you gain experience with Mathematica).

We'll focus on the Documentation Center where you can find information about all of the functions and deatures included in Mathematica. You can access the Documentation Center in various ways: through the Startup Palette link, through the Help menu at the top of the screen, or by using the keyboard shortcut <SHIFT-F1>.

In teh Documentation Center, you will see sections covering a variety of topics including Core Language, Mathematics and Algorithms, Visualization and Graphics, Dynamic Interactivity, Systems Interfaces & Deployment, Data Handling & Sources, and Notebooks and Documents as well as some additional links to indices, add-ons, etc.

Follow some of the links and explore some functions of interest. See how amazing a graphic you can construct. Also, explore what is available through the menus at the top of the screen including palettes that give you access to a family of functions by simplying clicking buttons.

While touring Mathematica, be sure to check out some of the items that we know will be of use (since we are beginning with a study of differential equations). Start by looking at the help entries for DSolve, NDSolve and Plot. Test out these functions and follow the links to look at related functions. For example, in class we solved the  1st order initial value problem (dy/dx)= (y^(1/2)), y(0) = 1using DSolve as follows:

soln = DSolve[{y'[x] ==Sqrt[y[x]], y[0] ==1}, y[x], x]

Execute this command and then use the trick of editing the output cell to create an input version of the solution. Incorporate this into a Plot command and plot the solution. Experiment with Options to control the range of the plot, add labels to the axes and whatever other embellishments you desire (plot in color or with a dashed line, add a title, ...)

Notice that an equation uses repeated equal signs ==, and a single equal sign = is used to assign values. Use the Documentation Center to find functions for which these symbols are used as abbreviations.

Overcoming Murphy: 
The Mathematica Programming Language

No matter how familiar you get with Mathematica's built-in function, add-on packages, and notebooks or packages you find via the internet or other sources, eventually Murphy's law will prevail: At some point, the function you need will not be there.

Mathematica deals with this in the most effective way possible by including a full-blown, multi-faceted programming environment. If you are accustomed to prodedural programming in a language like C, such procedures are supported. If you are used to manipulating lists in a language like Lisp, list operations are supported. As you will see later, Mathematica is especially useful as a pattern matching language. See the "Mathematica as a Programming Language" part of the tour for some examples.

Some simple programming background.

Before you start programming, there is one thing to know. You can easily write code that unintentionally requests a very difficult or impossible evaluation. If you get no response to your input, use <ALT-.> (Alt and Period depressed together) to abort a calculation. You can also try the interrupt and abort selections in the Kernel menu.

Internal representation: Everything is an expression.

Clear[x,y,z] (* Get rid of any old definitions *)

x^2

FullForm[%]

Internally, everything is an expression and is represented in the form Head[...].

Assignments: Immediate (for defining parameter values) and delayed (for defining functions)

x

Immediate assignment:

x=2;       (* Assign the value 2 to expression x *)

x  (* What value does x have? *)

x^2 (* What is the value of x^2? *)

y = x ; (* use = for immediate assignment *)

y (* Now what value does y have? *)

x=3 (* Assign a new value for x *)

y (* Does the value of y change? *)

Delayed assignment (useful for defining functions)

Clear[y] (* Wipe out old definitions *)

y (* Check that there is no value assigned for y *)

(* Double check - y is a global variable, but has no definition *)
?y

(* Note that x does have a definition since it was assigned a value *)
?x

y:= x (* use := for delayed assignment *)

y (* What is the value of y? *)

x = 8; y (* Assign a new value for x and see if y changes value. *)

Defining functions and rules

To do some mathematical operation once, it is usually easiest to just type in the desired expression. For example, we typed x^2 to square x. However, to perform the operation repeatedly, there are other useful approaches. We could write a function to do the operation. (Remember that internal operations start with upper case, so if you name your functions starting with lower case, you will avoid "collisions".) Let's write a function to compute squares:

(* This line defines how the function operates on a generic argument *)
square[x_] := x^2

(* Check that the definition was created *)
	?square

(* Now test it out by calculating a product of squares *)
			square[x]   square[I ρ]

You can also operate on expressions using rules that seek pattern matches and replace the matched patterns in specified ways. The line below says subject the expression x to a rule that replaces an expression by its square. 
a_ is the generic argument. 
"/." is shorthand for Replace.
Everything after "/." is the rule that replaces a generic argument with its square.

x /. a_ -> a^2

The result is 64, as expected, but what is the current value of x?

x

It has not changed. No assignment took place. Alternatively we could assign a new value to x based on the result of the rule.

(* Assign new value based on result of replacement rule *)
	x = (x /. a_-> a^2)

x (* Check that x has a new value *)

Linear Algebra

In the not too distant future, we will be studying linear algebra, and a tool like Mathematica can be very useful there as well. A couple examples are presented below, but you are encouraged to explore other capabilities through the Help facilities. (Explore the Palettes available under the File menu. Palettes such as Basic Input or Basic Typesetting provide tools for formatting vectors, matrices, etc.)

Construct a 3 x 3 matrix. Mathematica organizes things in lists indicated by curly braces { }, so the matrix is represented internally as a list of lists. Note that regular parentheses ( ) are used for grouping and indicating precedence of operations and square brackets are used to contain arguments of functions. (Note that you can specify output format with whatever kind of brackets or parentheses you desire.)

a = (({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))

MatrixForm[a]

b = (({{10}, {11}, {12}}))

MatrixForm[b]

x = LinearSolve[a,b]

a.x

Application to Differential equations

Do the following exercises and turn in your results as part of HW#2.

1) Pick 2 problems from HW#1 and use Mathematica to produce the solution.

2) Assign initial conditions as necessary, and plot particular solutions corresponding to your results from problem #1.

3) For one of your examples, solve again but this time obtain a numerical solution. (Look up NDSolve and use it.) Make a plot of the numerical solution together with the analytic solution. What can you say abou the accuracy of your numerical solution?

4) Following the example discussed in class, plot the direction field for the equation for the following differential equation: x'' - ϵ(1-(x^2))x'+x=0. 
a) Start with the simpler (linear) case when ϵ = 0. Sketch a trajectory based on the direction field. What are the actual solutions of the linear equation and what do the  trajectories look like in the phase plane?
b) Now let ϵ = 0.25. Again plot the direction field. Sketch some trajectories in the phase plane. Compare the behavior with the linear case. What qualitative change occurs? What does the solution look like? Does it depend on the initial conditions?
c) Now let the nonlinearity be larger, say ϵ = 10. How does the direction field change? What does the solution look like? Does it depend on initial conditions?