Getting started in Mathematica

Comp110 Course Module 1

Survival skills for Mathematica

This module begins our process of learning to use Mathematica as tool for solving and presenting solutions to problems that arise in Science and Engineering.  Mathematica consists of two main parts;  a front-end and a kernel.  The front-end is a set of windows that allows the user to view Mathematica files, called notebooks, and manipulate the contents of these notebooks.  The kernel is a set of core mathematical functions that Mathematica uses to compute the value of expressions that appear in Mathematica notebooks. Across the top of the screen is a thin, but wide window that contains a number of pull-down menus.  These windows can be used to

Open and save notebooks (File).

Edit the contents of a notebook (Edit).

Format the contents of a notebook (Format).

Organize and manipulates cells, the building blocks of a notebook (Cell).

Create graphics for the notebook (Graphics).

Control evaluation of expressions in the notebook (Evaluation).

Open palette design to simplify common tasks (Palettes).

Manage the layout of multiple notebooks on the screen (Window),

Provide helpful information about Mathematica (Help).

Instead of exploring each of these menus in detail, we will focus on a few key survival skills for Mathematica which can be accessed through these menus.

Saving your work

Perhaps the most critical task is saving your work.  The File menu has several options for saving a Mathematica notebook. Save will simply save the notebook into its current location.  For notebooks first opened via a download from the web, the notebook usually resides in a temporary directory local to the machine on which you are currently working.  Since you will switch machines between classes, this location is not a safe place to store your work.  Instead, use Save As to save your work to the directory My Documents.  For the PCs in Symonds Lab, My Documents is automatically linked to your Owlnet directory.  In the interest of good organization, I suggest that you create a Comp110 directory in My Documents where you will save all of your notebooks.

Exercise

As another general piece of good advice, I suggest that you save your work frequently.  Computers (especially running Windows) have a bad habit of misbehaving at the most critical time (say after you have done an hour of unsaved work).  I suggest saving your work at least every 15 minutes.

Printing your work

Another critical task is printing out your notebooks to be turned in for grading.  Symonds II contains two printers that can be accessed from the Print command in the File menu.  You can select either the east or west printer from the list of printer names on the small window created by the Print command.

Exercise

A printed version of your modules will be due at the beginning of class. Since printing out the modules takes a few minutes, either print them out beforehand or come to class early enough to print them out before class starts.  Arriving late to class and then trying to print out your module makes me very cranky and prone to start imposing draconian turn-in policies.

Getting help

The Documentation Center that is accessible from the Help menu will become your best friend in this class.  Since the midterm and final exams will be done in Mathematica, becoming an expert at using the Documentation Center will make your life much easier.  The main menu for the Documentation Center provides an overview of the capabilities of Mathematica.  Another way to access information about a function is to simply to type its name into the blank line at the top of the Documentation Center window and click the Mathematica icon to the left.  The Documentation Center will search for and return links to relevant topics in its library of helpful information.

Exercise

The Documentation Center contains a number of tutorials on relevant topics in Mathematica.  Instead of rehashing them in our notebooks, I will simply provide a hyperlink to the relevant tutorial or explanation.  In Mathematica, hyperlinks are always highlighted in blue.

Exercise

Controlling computation in Mathematica

One final skill is learning how to control computations in Mathematica.  As we noted in the previous module, Mathematica has no notion of an undefined variable.  While the idea that computation corresponds to simplification of an expression makes Mathematica an extremely powerful language, this paradigm sometimes causes Mathematica to strain mightily to simplify or evaluate an expression in which the user has unwittingly made a simple mistake such as accidentally inserting an undefined variable.

In such cases, Mathematica may take a long time to find what it thinks is the correct answer to an erroneous input expression.  If Mathematica "hangs" and fails to return a reasonable answer in a moderate amount of time, this situation is often the case.  To help deal with this problem, you may abort a current evaluation by selecting the Abort Evaluation option from the Evaluation menu.  (This command also has the keyboard shortcut Alt+. .)

Exercise

While[True,1]

Occasionally, Mathematica may also run slowly due to the presence of lots of complex Manipulate commands.  Mathematica uses much of its computation power dynamically updating the output of these Manipulate commands (even if the user is not manipulating the sliders.)  If Mathematica seems to be laggy, you should try disabling Dynamic Updating in the Evaluation menu.

Exercise

Manipulate[x!,{x,0,100,1}]

Numerical calculation in Mathematica

As mentioned in the previous notebook, Mathematica at its core is just a very sophisticated calculator.  To use this calculator, you need to create (or reuse) an Input cell and enter an expression.  Hitting Shift+Enter then evaluates the expression in the cell and returns its value (a simplified version of the expression).

Mathematical expressions in Mathematica can be entered in TraditionalForm that mimics traditional mathematical notation.  For example,

1+1

TraditionalForm is supported by Mathematica to allow users to enter simple expressions in the way in which they are accustomed.  Internally, Mathematica represents all expressions in StandardForm.  This form consists of expressions of the form Function[(Subscript[arg, 1]),(Subscript[arg, 2]),…,(Subscript[arg, n])].   For example, the expression 1+1 in StandardForm is

Plus[1,1]

There are two points to make about StandardForm. First, all Mathematica function names start with upper case.  (To distinguish your functions from Mathematica's, you should always use lower case.)  Second, the parameters to the function (the (Subscript[arg, i])) are contained inside square brackets, not parentheses.  Specifically, Mathematica uses [] for functions and () for grouping inside expressions.  Square brackets and parentheses are not interchangeable.  For example,

Plus(1,1)

yields an error.  This error is indicated by the red bracket on the right-hand side of the cell with a small square labeled with a +.  To view the error message associated with Mathematica's evaluation, you can click on the + to expand the cell.  Confusing the usage of square brackets and parentheses is the most common error that a novice Mathematica user makes.  Please remember the difference.

To start learning the basics of evaluating mathematical expressions in Mathematica, review the Mathematica tutorials contained in the introduction to Numerical Calculations from the Documentation Center.  You should spend a couple of minutes working over each of the seven short tutorials there and then do the exercises below.

Exercise

Exercise

Exercise

Exercise

Algebraic computation in Mathematica

One fundamental feature of Mathematica that separates it from other languages like Java or Matlab is its ability to perform not only numerical calculations, but also algebraic calculations.  This ability arises because Mathematica treats a mathematical expression as something to be simplified as opposed to something to be evaluated numerically.  Thus, Mathematica is easily able to evaluate

((x+x)/x)

without having a specific value for x.   Please spend 20 minute browsing the tutorials in Algebraic Calculations.  You do not need to know this material in depth.  Instead, you simply need to know where to look to answer the following questions.

Exercise

Exercise

Exercise

Given its ability to manipulate algebraic expressions, Mathematica is also well-suited to solving systems of algebraic equations.  We will leverage this capability often in this class.  The bread-and-butter function for this task is Solve.

Solve[2x+1==0]

Before pointing you towards the Document Center for more reading, let me make two points about equations in Mathematica.  First, Mathematica uses double equals (==) for equations and single equals = for assignment.  Confusing the two is another common mistake in Mathematica.  Note what happens if we replace == by = in the expression above.

Solve[2x+1=0]

Solve (and many more Mathematica) functions can take not only a single equation as input, but also a list of equations.  Lists in Mathematica consist of a sequence of expressions, separated by commas and enclosed by curly brackets.  For example,

Solve[{x+y==4,x-y==0}]

We will learn much, much more about lists in subsequent modules.   For now, briefly review the following tutorial on Solving Equations and do the following exercises.

Exercise

Exercise

Exercise

Document creation in Mathematica

Up to now, we have focused on Mathematica as a powerful calculator.  However, this is just the start of Mathematica's capabilities.  Mathematica also serves as a full-fledged document preparation environment that incorporate text, equations, figures and graphics.  In this section, we discuss some of Mathematica's more important features for document preparation.

Cells

A Mathematica notebook consists of a sequence of cells.  Each cell has a particular style associated with it.  To view this style, you first select the cell by clicking on the square bracket bounding the cell on the right side of the window.  Next, select the Format menu and the Style submenu.  The resulting drop-down menu lists the possible cell styles for the current notebook and has a check mark next to the style associated with the selected cell.  You may change the style of an existing cell using this menu or set the style of a new cell (created by clicking between existing cells).

In most notebooks there are two important types of cells, Input cells and Text cells.  Input cells contain Mathematica expressions waiting to be evaluated (and are colored in orange in this notebook style).   Hitting Shift+Enter in an Input cell causes Mathematica to evaluate the contents of the cell and produce a corresponding Output cell.  On the other hand,  Text cells do not contain expressions that are destined to be evaluated.  Instead, they contain text and formulas that are meant to be read.

As you progress in this class, I will ask you to add text cells to your notebook to answer questions and document your Mathematica functions. A common beginner mistake is to type text into an Input cell.  Since Mathematica interprets this text as an algebraic expression, the result often looks strange.

As you progress in this class,I will ask you to add text cells to your notebook to answer questions and document yourMathematicafunctions.A common beginner mistake is to type text into anInputcell.SinceMathematicainterprets this text and an algebraic expression,the result often looks strange.

Another common beginner mistake is to punch all of their text into a single Text cell and try to format the text inside the cell.  A better method is to treat each Text cell as a single paragraph and let Mathematica handle the typesetting using the options in the Format menu.

Some cells such as the "Document creation in Mathematica" cell above act as titles or section heading that cause cells to be grouped together hierarchically.  If we select this cell and check its style, we note its style is Section.  All text cells in between two section cells make up the body of this section.  You can expand and collapse this section of the notebook by double clicking on the right bracket associated with the section heading.  Adding cells for titles and sections makes your notebook look more polished.

For more information on cells and notebooks, you should take a brief look at the tutorial Notebooks as Documents.

Editing

Mathematica supports all of the standard cut and paste operations common in most Windows applications.  These operations can be accessed through the Edit menu.    One particularly important operation that you should remember is Undo.  Mathematica supports one round of Undos.  So, if you think that you have made an editing mistake, stop and think for a second before blindly proceeding.  Then use Undo if you think it is appropriate.

Another useful trick involves selecting a portion of a mathematical expression (for either copying or deletion).  One option is to click and drag to select the desired subexpression.  One drawback with this approach is that matching up square brackets, parentheses and curly brackets can be tricky for large expression.  A better alternative is to click inside the desired expression and repeatedly click.  Mathematica will automatically select larger and larger subexpressions that contains the cursor.  This approach avoids the problem of balancing parentheses.

Finally, you will often be asked to evaluate an expression contained in a Text cell.  Instead of trying to retype the expression into an Input cell by hand, I suggest that you cut and paste the expression into an Input cell.  Why?  Because retyping the expression often introduces a mistake into the expression that will make your life miserable later on when trying to understand why your answer is incorrect.  Always cut and paste if possible.

Creating 2D math expressions

Another feature of Mathematica is its ability to typeset mathematical expression in a quick and easy to use way.  For novice users, the easiest way to create 2D math expressions is to use the BasicMathInput palette from the Palette menu.  This palette contains most of the interesting expressions that you might like to create.

As you become more proficient at using Mathematica, you will start to become interested in using keyboard shortcuts to create most of these expressions.  Many of these shortcuts involve using either the control key or the escape key.  Take a brief look at the tutorials Entering Two-Dimensional Expressions and Entering Two-Dimensional Input for more a detailed description of how these shortcuts work.

An interesting thing to note about typesetting in Mathematica is that, if done properly, the resulting expression can be evaluated by Mathematica as input.  For example, is ∫Cos[θ]dθ equal to Sin[θ]?  We can cut and paste these two expression and enter the operator == from the BasicMathInput palette and arrive at

∫Cos[θ]\[DifferentialD]θ==Sin[θ]

Note that Mathematica returns True, acknowledging that this is an identity that holds for all θ.

Figure creation

The final ingredients in any well-done report or presentation are compelling 2D and 3D figures.  While text can be useful for explaining a concept, nothing beats a nice figure.  In many of your modules, the bulk of your work will be building visual elements that help explain and interpret your answers.

The simplest way to create a 2D figure is to use the New Graphic command in the Graphics menu.  To use this feature, place your cursor inside an existing cell (or create a new one) and select New Graphic.  Mathematica will insert a resizeable rectangle corresponding to the figure.  To add content to the figure, select Drawing Tools from the same menu.  This action will open a palette that allows you to draw lines and shapes as well as add text and formulas to your figure.  The elements of your figure can be selected, copied, pasted and deleted using the standard commands from the Edit menu.  You may also group/ungroup and bring to front/back elements of the figure using the operations submenu.  Finally, you can edit the properties of a selected element(s) using the Graphics Inspector.

Another way to create a nice figure is to edit the output of a Mathematica graphics function.  For example, the Plot command

Plot[((Sin[6x])/x),{x,0,2π}]

produces a Graphics object as output.  We can copy this object to a new cell and add a text tag using the Drawing Tool.  Note that the background color changed, since the cell type changed from an Output cell to an Input cell.  Try editing my text!

You now have an idea of most the tools available in Mathematica to create cool looking documents.  Instead of assigning you lots of little problems, I want you to focus on a single big problem to test how much you have learned.

Problem