Introduction to Mathematica for Scientists and Engineers

IMSE Chapter 1

IMSE-01(Intro).nb
General Introduction to Mathematica
RCH 7/19/01
revised 6/10/02 - rjerwin

Introduction to Mathematica for Scientists and Engineers (IMSE) is a series of Mathematica Notebooks designed to introduce scientists and engineers to Mathematica.  The Notebooks are interactive in the sense that they contain various Mathematica commands that the reader can activate to explore how Mathematica works.  In certain places the reader is invited to type in other Mathematica commands to try out various features.  My goal is to provide a "bare bones" introduction that focuses on the aspects of Mathematica that are most useful for the kinds of calculations that scientists and engineers do.  Mathematica is a very powerful system with many capabilities.  No introduction of tolerable length can hope to cover all of them.  Even Stephen Wolfram's weighty book on Mathematica hardly does it justice.  Wolfram provides a valuable reference, but not a good way to learn the system.

In writing these notebooks, I have kept in mind the (many!) places I stumbled or was confused in first using Mathematica.  Like all powerful computer tools, Mathematica has its quirks.  Some of these can take you by surprise.  Some are just annoying.  Others can leave you frustrated for long periods of time.

First, let's look at some structural features of a Mathematica notebook.  You probably have noticed the blue brackets at the right of the Mathematica window.  These blue brackets define cells.  There are many different kinds of cells in Mathematica.  The current type of cell is called a "text cell" because (surprise!) it contains text, rather than mathematical operations.  (To see the variety of different types of cells, click on Format on the menu bar at the top of the window and then on Style.  The menu lists the cell styles available to you.  As we proceed you will notice that different types of cells have different geometric figures at the top of the cell bracket.)

The following cell (with the bold face type) is called an Input cell and contains a command for Mathematica to execute.  Put the cursor anywhere within the cell or click on the cell bracket to the right.  (It will then be highlighted.)  Then hit the Shift+Enter keys (that is, hold down the Shift key and hit Enter) on the main keypad.  Alternatively, you can use the Enter key on the numeric keypad.  We will call this procedure "activating a cell".

5 + 11

You probably noticed two things.  First, it seemed to take Mathematica a long time to add 5 and 11.  That time delay was caused by the startup time of the so-called Mathematica kernel.  If you now go back and activate the 5 + 11 cell again, the answer appears very quickly.  Second, Mathematica added an In[1]:= to the cell and an Out[1]= to the cell containing the result of the calculation.  You should also notice that Mathematica added an outer cell bracket to the In and Out cells showing that they are grouped together.

NOTE:  If you simply hit Enter (without the Shift key), Mathematica adds a new line to the cell.  The cell commands are not activated.

Double-click on the outer cell bracket.  You will see that the two cells collapse to one and that the lower part of the cell bracket changes form, adding a triangle to let you know that something is hidden away.  By double-clicking on the outer bracket again, you can re-expand the cells.  Collapsing grouped cells is a good way to make a long notebook look more compact.

Exercise:  Double click the outer bracket that surrounds all of the cells defined so far. What is left over?

NOTE:  You can remove a cell by selecting its bracket.  Then hit the Del key.  Try that with the Out cell generated above.

NOTE:  Whenever you want to quit your session, simply click on File on the menu bar and then on Exit.  Respond Don't Save to any request for saving changes so the IMSE notebook on your diskette is not changed.  If you want to save the changes you have made, please save them in a file with a different name.

As usual, you can change the size of the Mathematica notebook window by moving your cursor to one of the edges of the Window until the cursor symbol changes to a double-ended arrow.  You then drag the edge to expand the window.

Mathematica as a calculator

You can use Mathematica as a simple calculator.  Let's examine several kinds of operations.  As we do so, we'll learn something about the syntax of Mathematica operations.

Activate (Shift+Enter) each of the following cells to see what happens. Parenthesis with asterisks inside are used to denote comments.   (* indicates a comment that Mathematica ignores in evaluating the expression *)

5-11

5*11

5 11

The last cell illustrates multiplication implied by a space separating two quantities - it works, but it is not recommended!  It is too easy to misread and too easy to forget the space.  Activate the following cell to see what happens.

511

5/11

Perhaps that last result surprised you.  In many cases Mathematica will give you an "exact" result that may not be quite the form you expected.  The next cell has the same division operation, but the //N part is a so-called postfix operation that tells Mathematica to give the result in numerical form.  Try it out.

5/
        11//N

5^11

5 - 11/10

Did you expect to get what Mathematica gave you for the result? As in most computer languages, Mathematica has a heirarchy of operations: division is done before subtraction, for example.  Rather than trying to remember the heirarchy, it is better to use parentheses liberally to group the terms to implement the operations the way you want them implemented.  Parentheses also make the code easier to read.

(5 - 11)/10   
5-(11/10)

In Mathematica you can use the percent symbol % to refer to the most recent result.  This symbol is useful to reduce typing, but it can lead to difficulties if you forget what the most recent result was.  The next cells illustrate its use.

4/15

% // N

Everything seems to work well, but now activate the following cell and then go back to the %//N cell and activate it.

3/17

Very Important Lesson:  The order in which commands are executed is important in Mathematica.  In our example, when you activated the 3/17 cell, that became the "previous result" for the %//N cell.  The order in which the commands are written in the notebook is not the determining factor.  (If you want to refer to a specific result, use %n or Out[n] for the (n^th) output line.)  I prefer not to use the % symbol as a permanent part of a notebook because of that issue.  It is, however, quite helpful in experimenting with commands and in debugging a complicated set of commands.

Symbols and variables

Of course in most calculations, we want to use symbols rather than numbers to represent various quantities.  The cells below show you how Mathematica lets you assign numerical values to various symbols.  The scheme is the same as that used in most computer languages.

a = 7

Note that Mathematica gives an Out statement that tells you it has the number 7 associated with the symbol a.

a = 6;

Here we have changed a to 6, but Mathematica did not seem to respond.  That's because we used a semicolon (;) at the end of the statement.  The semicolon is used frequently in Mathematica to suppress unneeded Out statements.

To check that Mathematica has indeed changed the value associated with the symbol a, we can use a simple command line with just a.

a

The previous statement is equivalent to

Print[a]

By using Print, you can include a message to remind you of what is being printed.

Print["a = ", a]

Exercise:  In the Input Cell below, type and activate a command that prints a message "a/5 = " and then prints the numerical value of a/5.

Let's now define several symbols and then use them for some operations.  Activate the following input cells.  Explain what happens.

b = 3;
c = 2;
d = 4.4;

a + b^c

(a + b)^c

(a + b)^-d

Trigonometric Functions

Mathematica "knows" trigonometric (and many other) functions. These functions can be used in a variety of ways.  We will use this section to introduce you to some of the ways of using Mathematica's built-in functions.

Sin[1]

Sin[1]  // N

Note that the first cell didn't appear to do anything.  When the argument is an integer, Mathematica gives us the "exact" (but not directly useful) result Sin[1].  The second cell (with the //N) gives us the numerical value.  Does Mathematica use radians or degrees for the argument of the Sin function?

If you give the argument as a decimal number, Mathematica gives you the numerical value.

Sin[1. ]

The exact number "1" has infinite precision, so Mathematica must express the sine of this number as something with infinite precision -- hence the Sin[1].  The decimal number "1." specifies that the number 1 is to be treated as a machine-precision number.  Sin[1.] is therefore also a machine-precision number.  The default precision in Mathematica (which you can determine by typing $MachinePrecision) is 16.  Try typing and evaluating Precision[%] after Sin[1] and Sin[1.] above.

Some important points to note:
    1.  All of Mathematica's built-in functions begin with an upper-case letter.
    2.  The argument of the function is contained within square brackets [  ], not parentheses.  Parentheses are reserved for grouping symbols and numbers.
    3.  The arguments of the trigonometric functions are in radians.   Mathematica has a simple way of doing a conversion from degrees to radians: multiplying by the constant Degree converts the argument to radians.  See the cells below.

Sin[45 Degree]

Sin[45 Degree]  // N

Sin[a + b]

Sin[a + b]  // N

Note that Mathematica has remembered the values associated with a and b from earlier in our session.

Let's now use some trignometric functions in calculations.

Sin[45 Degree]^2

Note that the exponent is applied to the Sin function, not to the argument.

Sin[(45 Degree)^2] //N

Sin[
      Pi]

Tan[45 Degree]

ArcTan[1]

Tan[Pi/2]

Tan[Pi/2. ]

The previous two results show you how Mathematica handles large numbers.  The Pi/2 cell gives the exact result (precision = ∞).  The Pi/2. (with the decimal point) indicates that with the round-off error in handling the machine-number 2. in place of the exact number 2, we get a large, but not infinite value for the tangent of 90 degrees (and the precision is now 16, not ∞).

Exercise:  In the cell below type Tan[90 Degree] and then activate the cell to see what happens.

Other functions

Mathematica knows many standard functions (and some esoteric ones as well).  Some of the common ones are the exponential function Exp[] and the hyperbolic functions Sinh[], Cosh[], etc.  Try the following cells for a few examples.

Exp[2]
Exp[2]  // N
Exp[2. ]

Sinh[3.2]

Cosh[2.2]^2 - Sinh[2.2]^2

You can also generate "random" numbers.  The first command returns a random number between 0 and 1.  Try activating the cell several times.  You should get a different number each time.

Random[Real]

The following command gives a random real number between 2 and 20.  Note the use of the curly brackets {} to specify the range.  This is a common structure in Mathematica.

Random[Real, {2, 20}]

The next cell shows how you get a 1 or a 0 with equal probability but in random order.

Random[Integer]

The following cell shows a command that gives a random integer in the range 0 through 10.

Random[Integer, {0, 10}]

You can also "seed" the random number generator so that it generates the same random number when given a particular seed (here, the seed is the integer  2002).

SeedRandom[2002];

Random[]

SeedRandom[2002];

Random[]

This is a useful way of keeping track of your random numbers: even if you close and re-open Mathematica, or switch computers, the seed 2002 will always give the number 0.0171295.

Palettes

Mathematica has a nice way of making the typing of commands and mathematical expressions easier.  The system has built in "palettes" that have commonly used mathematical symbols displayed on them.  To have a palette displayed, pull down the "File" menu, select "Palettes," and then select the palette you want.  (You may have more than one palette displayed if you so desire.)   I find the BasicInput palette quite useful. It contains buttons for π, e (the exponential), i  ((Sqrt[-1])), integrals, sums, matrices, etc.

Exercise:  Look through the various palettes to see what is available.  Some of them have triangle symbols that look like ⊳.  That symbol  indicates there are more subpalettes hidden from view.  Click on the ⊳ and it will turn into a downward pointing triangle ▽ and the additional subpalette should appear.  Clicking on the symbol ▽ will hide that palette.

NOTE:  The same triangle symbols are used in Mathematica's Help to indicate that further information is available on a particular topic.

Quirks

In the various IMSE notebooks, I will point out some of Mathematica's quirks.  In most cases, these are minor faults and, once you are aware of them, they pose no fundamental difficulties.  Mostly they are syntax structures and default values that make perfect sense, but may nevertheless catch you by surprise.

Here I want to mention just one quirk associated with the text editor in the notebook window.  Occasionally I have found that the text editor (apparently) embeds some hidden character(s) into the commands you have typed.  This seems to occur (fortunately, only rarely) when you insert a new command in the midst of existing commands or when you hit Enter to go to a new line and the previous command line does not end with a semicolon.  When you activate the cells containing those commands, you get error messages, usually something like "Times Tag protected."  Also, you may see something strange in how the text editor indents the commands you have typed.  That is usually a signal that something peculiar is going on with the text.  The only solution seems to be to delete entirely the commands that are giving difficulty and to retype them.  That usually solves the problem.

Further Information - Help

You are encouraged to try out the features you have learned about by typing various expressions and evaluating them.  Using Mathematica is an experimental science.  The worst that can happen is that Mathematica freezes up, which it may do from time to time.  If that happens, use Ctrl+Alt+Del to stop Mathematica and to reboot your computer.

IMSE-02 through IMSE-05 are basic introductory material that is essential for almost all Mathematica work.  You can then look at the other IMSE notebooks as you need them.

IMSE-02(Functions) - how mathematical functions are set up in Mathematica
IMSE-03(SymbolicManipulation) - algebraic and trigonometric symbolic manipulations, symbolic solutions of equations, and symbolic calculus
IMSE-04(Plots) - an introduction to graphics, plotting functions, etc.
IMSE-05(Lists-Arrays) - two very important structures in Mathematica
IMSE-06(NDSolve) - numerical solution of differential equations
IMSE-07(Complex) - a brief introduction to the use of complex numbers and variables in Mathematica
IMSE-08(Fourier) - calculating the Fourier Power Spectrum of data
IMSE-09(Programming) - how to use Mathematica as a programming language
IMSE-10(Statistics) - using Mathematica to find the mean, standard deviation, etc., of lists of numbers
IMSE-11(I-O) - how to handle input and output to and from Mathematica

Mathematica's Help file contains lots and lots of information about Mathematica commands and how to use them.  It is also a useful source of examples of Mathematica commands, which you can Copy and Paste into your own Notebooks.