Getting to Know Mathematica

William M. MacDonald © 1999

Introducing Mathematica

In the analysis of a system much of what is called mathematics by scientists and engineers is better described as symbolic manipulation. Rather than proving new mathematical theorems, or even developing new mathematical techniques, much of the effort in analyzing a physical system is spent on transforming variables, working out series expansions, evaluating integrals, solving differential equations, numerically evaluating expressions, and creating graphs to present results. The purpose of a  computer algebra system (CAS) like Mathematica is to eliminate the drudgery of much of this "mathematics".  This allows the scientist or engineer to focus on identifying the important physical concepts and quantities,  making reasonable physical approximations to develop equations describing a system, and then identifying the most important features of the solutions.     
	In the foreword written for the book, ``Mathematica for Physics," by Robert L. Zimmerman and Fredrick I. Olness (Addison-Wesley, 1995), Stephen Wolfram, the developer of Mathematica, writes
   "To be good at physics you no longer have to be good at calculating.                                          
   When I started doing physics in the early 1970's (Wolfram was born in 1959!), it was generally thought that being able to do long calculations by hand was an essential skill.  But as it happens I was never very good at such calculations.  And so I looked for an alternative, and before long I found one: I discovered that I did not really need to do the calculations by myself--I could get a computer to them instead.  My physics papers from the late 1970's were full of elaborate calculations.  And from seeing this many people came to the conclusion that I must be a great calculator.  But in fact that was far from the truth, and what was actually going on was that I was doing all my calculations by computer."

Starting Up with Mathematica

The Mathematica system actually consists of two programs, the front end and the kernel.  The front end provides a friendly notebook interface for the user.  The kernel performs the numerical, symbolic, and graphical computations sent to it by the front end.   The front end records in a notebook both the input sent to the kernel for evaluation and the output returned by the kernel. These two programs actually run independently, but they communcate with each other using a protocol called MathLink. 
	The front end can be started up and used to read, edit, or even create a notebook without ever starting up the kernel.  In fact, the front end will not start the kernel until you are ready to begin calculations.  So, first learn how use the notebook interface to take advantage of using a Mathematica notebook as an interactive workbook to

1. state the problem you are tackling, 
2. give the background and equations that you need,
3. keep an accurate and clear record of your work and results,
4. be modified to include more information or better results,
5. share with others, and
6. use for reports and presentations.

Setting up a Notebook

The idea behind this section is to help you get started using notebooks in these ways.  You will learn to set up a notebook in sections and using cut and paste.  But if you explore the topics under Format,  you will discover many ways to enhance a notebook to make it more readable and to emphasize particular points by using colors, boxes like those in this notebook, and other tools.   Be careful if your notebook is to be printed, however, because some colors may obscure text.

Creating your notebook

Look at the Mathematica menu: File, Edit, Cell, Format, etc.  Click on each (put the mouse cursor on each, press the mouse button) and look at the submenu that appears.  Note that some items are checked; these are options that have been selected.  
	Create a new notebook by choosing File/New from the menu.  (The slash separates the main menu item from an item on the submenu.  Some submenus have subsubmenus and the slash will be used to separate each level of menus.) Next,  choose File/Save As from the menu. In the dialogue box that appears, select the drive and the directory where you want to save this Noteook.  Then change the name  to something else, perhaps Exploring Mathematica.  Finally, select OK or Save, or whatever your version of Mathematica uses. In the titlebar of the window now appears the name of the file where this notebook is stored.  The extension .nb is added automatically to indicate that it is a Version 3 notebook.

Organizing your notebook

Your notebook needs a title.  Also, you should give some thought as to how you want to organize your notebook, such as a project report with Introduction, Background Material, Theory, etc.  Or perhaps you are just going to tackle several problems in a course you are taking, like this one.  In either case, it will help you to set up your notebook following an outline of what you are planning to do. Here is an outline that you might use.

Exploring Mathematica
	Using a Notebook
	Numerical calculations
	Algebraic calculations
	Symbolic calculations
	Plotting
	Drawing figures

A notebook stores text, symbolic and numerical results, and graphics, each in its own cell.  Each cell is enclosed by a bracket on the right.  These cells are grouped into labelled sections and subsections by nested brackets that enclose the individual cells. The cells under each grouping can be "closed'' so that only the title of the corresponding section or subsection is visible when the notebook is opened.  This feature makes it possible for you to give a presentation using your notebook.  As you give the talk, you simply open and close sections of your notebook just as you would change transparencies or slides.

Title cell

With the mouse select the menu item Format/Show ToolBar.   A check mark will now appear beside this submenu item whenever you look at the Format menu item.  A toolbar appears at the top of window for your notebook.  A box on the left contains the word Input and several small boxes to the right have lines representing text that is flushleft, centered, flushright, and justified.  Click on the box with the word Input and see a list of all the types of cells that you can use to organize your notebook.   Click on Format⟹Style to see this same list -- but showing "quick keys" that you can use to choose the most common styles. 
	First, click anywhere in the main part of your notebook and see a horizontal line appear.   This is a "cell insertion point".  Next, go to the toolbar, click in the box that lists types of cells, and choose Title.  Finally,  start typing the title for your notebook.   You will create a Cell marked with a bracket on the right.. 
	If you create a cell insertion point and do not choose the cell type before you begin typing, Mathematica will create an Input cell to be evaluated.   You can change the type of any cell.   Click on the cell bracket to highlight it with a narrow black box.  Go to the toolbar and choose the type of cell that you want.

Section Cell

Use the down arrow to move the cursor out of the title cell.  You will see a horizontal line appear, indicating that you can start a new cell here.  (You can also use the mouse to move the cursor below the cell until the cursor becomes horizontal.  When you click the mouse you are in a position to start a new cell.)   Choose Section for this cell type and start typing the name of your first section, say "Using the Front End".

Text Cells

Write an explanation of what you are doing to help you to focus your effort and make your notebooks more useful records.  Move the cursor to a place just below the first section cell, click to create a cell insertion point, choose Text from the toolbar, and start typing something like this.
	"In this section I shall learn to use the Mathematica front end."
		A text cell has no "dingbat", the type is plain, and the text will be started at the left margin and will automatically wrap as you get to the end of a line.  You can use the Tab key to indent the first line of each new paragraph. If you have been entering text into an indented paragraph, hitting the Return key will automatically start a new indented paragraph for you.   	
	If you want to make a word bold, italicized, underlined, etc., just double-click on it and choose the style from Format⟹Face.  You can also color a word by choosing Format⟹Color. You can also click-and-drag over several words to select them for underlining or whatever. This means (1) click in the cell and hold down the mouse key, (2) drag the cursor across the text, and (3) release the mouse.  The selected text will be highlighted.

Explore text types

1. Double-click a word that you want to emphasize and choose a bold face.
2. Highlight a phrase and italicize it.
3. Click on the text cell bracket and choose Format⟹Face⟹Bold.
4.Highlight the text cell bracket and choose Format⟹Remove Options.  What happens?

Cut and Paste

You can change a notebook by deleting or copying cells and by pasting them somewhere else in the same notebook.  You can also copy or move any number of adjacent cells to a different notebook .  You can even copy an entire notebook.  
    	To copy  or delete any number of adjacent cells, just click and drag across all their cell brackets.    (You can't select cells that are not adjacent.)  Then use the Edit⇒Copy or Edit⇒Cut commands. Then, move the cursor where you want to place the cells in the same, or a different notebook, and use Edit⇒Paste.  When cut or copy cells,  no matter how many you choose, they are copied to a "clipboard". They remain there until you cut or copy something else. 
        	To copy  an entire notebook,  first use the File⇒New command to open a new notebook and then File⇒Save As set up a file for it.  Then, in the notebook that you want to copy,  highlight the bracket that encloses the title and all the cells in the notebook, or click and drag down cell brackets from top to bottom.   Use the copy command.    Then place the cursor in the other notebook that you have just created or opened and use the paste command.  Mathematica allows you to have as many open notebooks as the memory on your machine will support!  You can copy and paste freely from one to another.

Practice cutting and copying

1. Highlight the bracket of your text cell by clicking on it.  
2. Click on Edit in the menu and choose Copy.
3. Create a cell insertion point below your text cell.  Choose Edit⟹Paste from the menu. You should now see two identical text cells in your notebook.
4. Click on the bracket for one of your two text cells and choose Edit⟹Cut to remove one of these cells.
5. Click with the mouse anywhere in the cell that you copied to make a "text insertion point".  Then click-and-drag over some words to highlight them, use the quick key for Cut and see the words disappear.   Before you move the cursor use Paste, and see the words reappear.  Click somewhere else in the cell, or in a different cell, and use Paste.

Save your notebook

At fairly frequent intervals save a notebook that you are using for a project so that your work will not be lost if you do something that crashes your computer.   This is a good point to save this first notebook that you will be using to become familiar with the basic facilities of Mathematica.  Use the mouse to select File=>Save.  You do not want to use File=>Save As again because you have already created the file where your notebook is saved.

Running the Kernel

Click below the first section of your notebook, and the explanatory text to create a cell insertion poing.  Start typing the following expression.
	22.34 + 56.24.

As usual when you begin typing, you will see a bracket appear at the right side of this Input cell.  To evaluate the cell just leave the cursor anywhere inside it and use the key combination <shift-return> by holding down the "shift" key and hitting the "return" key, or hit the enter key on the right-bottom of your keyboard. (The return key simply starts a new line in a cell.)

There is a delay the first time that you evaluate an input cell in during a Mathematica session while the front end calls on the kernel to start work.  As soon as the kernel has started, you will see an output cell appear with the result.

Both the input and output cells will appear with a numbered label used by the kernel to index all the input and output that it has processed during a session.  These labels will be displayed while a notebook is open. Click on the menu item Kernel=>Show In/Out Names to turn off this option.  As this indexing of output suggests, Mathematica remembers every input and output cell in a session.  Even if you open another notebook, the numbering of input and output cells continues sequentially  from the beginning of your session.  Select the cell where you entered  22.34 + 56.24 and evaluate it again.  The numbers of both the input and the output cells change.  But Mathematica still remembers the previous input and output cells.  	As this indexing of output suggests, Mathematica remembers every input and output cell in a session until you shut down the kernel by selecting Kernel=>Quit Kernel from the menu. Even if you open another notebook, the numbering of input and output cells continues sequentially  from the beginning of your session. Place the cursor anywhere in the input cell above and evaluate it again (shift-return or enter).  The numbers of both the input and the output cells change.  But Mathematica still remembers the previous input and output cells.

You can access the nth output in a session, no matter in which notebook it appeared, by entering the expression Out[n] or the shorthand %n. Enter the expression. You can also call up any previous input and evaluate it again by entering the expression In[n] into a cell and evaluating it.   However, you won't see the actual expression that you entered into the nth input cell.  If you want to recall that, use the command InString[n].  The output cell will contain the expression in the nth input cell. 
	The shorthand command for recalling the output from the last command that you entered is %, and you may be tempted to use this frequently.  However, you can get into trouble if you are jumping around in a notebook, changing some input cells and evaluating them again.  The point is that % refers to the output from the cell that you last evaluated, not from the cell above the one where you enter the %.
	There is a serious problem with also with using Out[n] or %n.  If you save a notebook and then open it in some later Mathematica session, all the output cells will have different numbers.   So you will not get the same results if you try to evaluate the notebook again unless you follow the same sequence of operations.

Exercises

1. Evaluate the expression 13 / 45.
2. Copy and paste the previous input cell, then go into the new cell and put a decimal point after the 45 and re-evaluate the cell.
3. Go back to the first input cell and wrap the input with N[   ], i.e. N[ 13 / 45 ]. Evaluate it.

Quitting the kernel

Before you run any program, always make sure you know how to stop it if it gets caught in an infinite cycle or a poorly formulated computation that takes too long.  From the menu choose Kernel=>Abort Evaluation.  A "hot key" for this command appears beside this menu item.  If the kernel is too busy it may ignore your command to abort.   An alternative is to use Kernel=>Quit Kernel to shutdown the kernel.  Before you do this, however, use File=>Save to save your notebook.  Since the front end runs independently of the kernel, it can save your notebook while the kernel is carrying out a calculation.  You can then shutdown the kernel without losing any part of your notebook.  
	You can return to working in your notebook without quitting Mathematica by choosing Kernel=>Start Kernel=>Local from the menu. Shutting down the kernel, however, removes from the computer memory all the input and output processed during a session.  Of course, all input and output has been stored as text in the notebook, so it has not been lost.  But to continue with your investigation, you must restart the kernel and have it again evaluate all input to restore its memory.  The easiest way to evaluate all the cells in a section is to click on the bracket that encloses all the cells in the section and then use the <shift-return> key combination that causes the kernel to evaluate all the Input cells.

Getting Help from Mathematica

Symbols  in Mathematica

All names for built-in symbols (constants, variables, functions) begin with a capital letter or a dollar sign $.  In compound names both words begin with a capital letter, and Mathematica  is sensitive to case.  Examples are the following:

Tan	
	ArcTan 
	ReplaceAll
	RepeatedReplaceAll

System variables are prefaced with a dollar sign, "$".

$Version
	$Path
	$MachineEpsilon

Help

The symbol ? requests help.  It can be used to list symbols (constants, variables, functions) and to get information about them.

Listing symbols

In using ? the asterisk *  is treated as a "wild card".

Here we list all symbols provided by the system that begin with the letters "Fac".

?Fac*

Here we ask for information about one of these symbols.

?Factor

However, symbols that you introduce are listed by using this command.

?Global`*

The symbol Global` stands for the Context, that is the "workspace", assigned to you by Mathematica.  The contexts that are being used are given by executing this system variable.

$ContextPath

Exercises

Loading a Package of additional constants and functions always opens a new context.

Needs["Miscellaneous`PhysicalConstants`"]

$ContextPath

?Miscellaneous`PhysicalConstants`*

Ask for information about a symbol.

?AccelerationDueToGravity

Look at the value of this constant.

AccelerationDueToGravity

Exercises

Using Symbols

You don't have to type every symbol out in full when using Mathematica.   Just type the first few letters and select Input=>Complete Selection from the menu. (Note that there is a quick key listed beside this command.) Click on the symbol that you want.  If you don't quite remember how to use some function, type its name and choose Input=>Make Template.   There is also a quick key for it.

Exercises

The Browser

The manual for Mathematica is "The Mathematica Book" by Stephan Wolfram, published by Wolfram Media and Cambridge University Press in 1996.  To open this book choose from the menu Help⇒Mathematica Book.  Displayed in the left-most column are the titles of the major sections of this book. Clicking on "Contents" in this column displays a table of contents that lists every section of the book.   The section titles are so descriptive that you can immediately see that this is the place to start when you want to learn how to do anything with Mathematica.

Open any section of the book by clicking on the title.  As you will see immediately every topic is explained by a series of examples rather than a lengthy verbal explanation.  Moreover, you can work in the Browser without contaminating it.  For example,  open section 1.1.1 entitled "Arithmetic", click with the cursor in the first input cell that has the expression 2.3 + 5.63, and change the 5.63 to 21.5.  Evaluate the cell and you will see the new result.  You will also note that the In and Out indices have changed.  Now create and evaluate a new input cell below the one you have just evaluated.  After doing this, click on "Practical Introduction" at the top of the second column to display just the topics in the section "A Practical Introduction".  Then return again to section 1.1.1 from this listing of sections by again clicking on "Arithmetic".  You will see that this section of the book has been restored to its original.

Therefore, the Browser provides an interactive manual where you can not only see examples of how to use Mathematica to do what you want, but a notebook where you can actually practice.

Exercises

1. Choose Help/Help... from the menu.
2. In the dialogue box that opens, click on the button for Built-In Functions. Choose Numerical Computation from the left-most column, Numerical Evaluation from the middle column, and N from the third column. 
3. Read the information about N.  
4. Scroll down in the window and click on the triangle after Further Examples. Go down below these examples and enter the expression N[Pi , 30]. Evaluate the cell.
4. Note the words with blue underlines just below the text about N, indicating links to related information.  Choose Chop.  Read the information about this function. Look at the further examples for this symbol.
5. Chase down the link to Round and read this material.

The Mathematica Language

The Mathematica language is based on certain concepts and elements that unify its handling of numerical, symbolic, and graphical operations.  Knowing these elements and understanding how Mathematica uses them will make it easier for use Mathematica and take full advantage of its capabilities.

Structure of the language

The key to understanding Mathematica is that it operates by accepting "expressions" made up of "atomic objects", applying "rules" for transforming or rewriting these expressions, and then returning the resulting expressions.

Atomic objects

Symbol	x , f, Earth Radius, Tan
	Integer		3
	Rational	3/4
	Real		3.0
	Complex	3 + I 4
	String		"Bill"

Conventions for symbols

In Mathematica the term "symbol" is used to refer to a named object.  The identifier/name for a symbol must begin with a letter, lower case or capital, but can be followed by any sequence of letters and digits.  The underline _ is  a symbol used by Mathematica and therefore must not be used in a compound identifiers, that is, an identifier made up of two or more words or word fragments.  Instead, the Mathematica convention is to capitalize the first letter of each word or fragment of a word in a compound identifier.  Capital and lower case letters are distinguished.  These are acceptable and distinguishable identifiers.

Tan	
ArcTan 
ArithmeticGeometricMean

The manual advises users to avoid conflicts with system symbols by using identifiers that begin with a lower case letter.  However,  since Mathematica symbols are protected, the user can not inadvertently change the rules associated with a system symbol and a warning is displayed if it is attempted.  So there is no reason not to use identifiers that begin with a capital letter.  
	In fact, a warning is issued even if two similar identifiers are used.  These warnings can become an annoyance.  Prevent these warning by placing the following command at the beginning of a notebook.

Off[General::spell,  General::spell1]

Expressions

Every input and output is called an expression.  Expressions can be entered in a form called StandardForm that closely resembles mathematical notation and the output can also be in this form.  However, every expression is represented internally like this.
		h[ x , y, g[u,v,w] ]
In this expression the symbols h and g are heads.   The internal representation of an expression can be displayed by using the symbol FullForm.

FullForm[(x^2) - 4 x  + 3]

Analogy to mathematical notation suggests that the head of an expression is like a function or a procedure, namely,  a symbol that has been given a set of rules to use in producing output from its arguments.   Here is an example.

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

But the head of an expression can be simply a label.  For example, Mathematica uses the symbol List for storage of sequences of numbers, symbols, expressions, graphs, etc.  Here is a an example.

{a, b, c}

This is how this object is represented internally.

FullForm[{a, b, c}]

Here are more examples.

Input Form	FullForm
	     a+b		Plus[a,b]
	  ab or a*b	Times[a,b]
	    a=3		Set[a,3]
	    a:=3		SetDelayed[a,3]
	    a-> 3		Rule[ a , 3]
	  {a,b,c}	List[a,b,c]
	data[[i]]	Part[data,i]

Rules

A rule specifies how a symbol is to be transformed when it appears in an expression that is evaluated.  For example, evaluation of the following cell

f=(x^2)+ x Sin[x];

attaches to f a rule that Mathematica will apply when evaluating any expression in which f appears, like the following one.

(f^2) - f + f/2

Rules can also be used to evaluate a particular expression instead of assigning them to some symbol.  First clear the symbol f and then apply a transformation rule for evaluating the above expression.

Clear[f];
((f^2) - f + f/2)     /.   {f -> 
          (x^2)  +  x Sin[x]}

The symbol /. is a symbol causes the rule that follows it to be applied to the expression that precedes it.  Several rules can be applied.

x + y /. {x -> y, y -> v}

This shows that each rule is applied to the original expression.  If you want rules applied repeatedly until the result no longer changes, use //. to apply rules to an expression.

x + y //. {x -> y, y -> v}

Mathematica for Technical Writing

You can typeset expressions in a notation closely resembling conventional mathermatical notation.  A simple introduction to using mathematical notation is given in Section 1.1.7 where you will learn about using a "palette" as well as typing Greek letters, powers, etc.  Note that there is a certain logic to the scheme developed for typing symbols.  For example, the standard notation for a power in symbolic algebra programs is 
		x^2
and this is accepted by Mathematica.  Note that you enter the caret by using shift-6 on the keyboard.  To typeset this as x raised to a power use ctrl-6 instead.  As you do this you will see a shaded area cover the x and a superscript that is a box enclosing a black square. As you type "2" it replaces the box.  To return to "ground" hit the right cursor key.  If this is just the first part of a mathematical expression continue typing and the shaded area will grow as you do so.   The correct spacing will automatically be entered before and after symbols and a mathematical font will be used.  When you are finished and want to leave the shaded area, hit the right cursor key.  You will then see something like this.
	(x^2) - 2 x y + (y^2)
To go back into an expression to change it, place the cursor just in front (behind) the expression and start hitting the forward (backward) cursor key.  You will see the shaded area reappear and the insertion point will move all the way through the expression, upward into superscripts and downward into subscripts.
	You can read more about the use of mathematical notation in Section 1.10.  For examples of typesetting, look through the topics in the "Formula Gallery".   The contents are display in CG.1 .