Mathematica Basics

Author: Barry McQuarrie
University of Minnesota, Morris
Jan 2015

This document contains examples to help you get started with using Mathematica 10.

Under the HELP in Mathematica, you can find a wealth of information. Too big a wealth, if you are just starting out. For that reason, I collect here some basic ideas to get you started, and you should get in the habit of using the HELP command as you find necessary. Mathematica is a very powerful computer algebra system (CAS) that can do many things for us (as we shall see). But if we do not understand the mathematics behind what we ask  Mathematica to do for us, we can very easily misinterpret our results. You should think of Mathematica as a tool to help you improve your understanding, not as a machine which will do your understanding for you!

Mathematica Cells

The blue brackets on the right represent a Mathematica cell. If you can’t see them, move the mouse over to the right side until they appear. You can double click on these blue brackets to expand and collapse cells. Try it, and you will find that cells which contain other cells can be expanded or collapsed. The little blue triangle at the bottom tells you there is more information in the cell, so double click on it to expand it. Knowledge of this cell structure is not very important when you are first learning Mathematica, but you need to know it to open the cells below which contain information on using Mathematica.

Entering Input

When you start Mathematica, you are presented with a window into which you can enter commands. The commands are processed by the kernel, which is started when you first ask Mathematica to do something. You ask Mathematica to "do something" by pressing SHIFT-ENTER, or alternately the ENTER key on the keypad. Let's enter the number 2:

2

You can refer to previously entered data either by the input number (1 in the above) or using the % key (which refers to the last OUTPUT):

In[1]

%

You can use multiple % to refer to output before the previous output:

1

2

3

%%%

%%%

%%%

You can also refer to the Out[ ]:

Out[6]

Arithmetic

Mathematica can be used as simple calculator.

4+6

4-6

4*6

In Mathematica, a space also denotes multiplication. This can lead to confusion, and you should always think about exactly what it is you are telling Mathematica to do when you encounter problems!

4 6

4/6

Notice that Mathematica leaves the result in the most accurate form if you use integers. If you use decimal numbers, Mathematica will produce a truncated decimal result.

4/6.

Powers are defined with the ^ symbol.

4^6

Assigning Value to Variables

You can assign a value to a variable in two ways. The first immediately makes the definition:

a = 3.4

a

The second makes the definition only when the variable is later requested (that is, the definition is not immediately processed by the kernel):

b := 6.8

Notice there is no output from this! When we ask later for the value of b, the kernel processes the assignment and returns the result.

b

Once a variable is defined in the kernel, it is defined even if you open another window!! Try it. This is usually the problem when Mathematica behaves (seemingly) strangely. You can remove a definition in the following way:

Clear[a,b]

a

b

Defining Functions

Here is how you define a function in Mathematica:

f[x_] =4*x/3

Notice the square brackets in the definition, and the underscore. 
Square brackets [] are used by Mathematica to define functions, 
round brackets ( ) as delimiters (ie, for multiplication), and 
curly brackets { } for lists.

You can refer to the function by typing f[x]:

f[x]

You can make substitutions for the variable itself:

f[x-3]

f[3(x/2)^2]

f[t]

a:= 3

f[a]

f[1]

f[1.]

Defining a Piecewise Function

Here is how you define a piecewise function in Mathematica:

f[x_] =Piecewise[{{x,x<0},{x^2,0≤x≤2},{x-4,x>2}}]

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

Capitization

Mathematica is very picky about the syntax you use, even to the point of capitalization.

f[x_]=(x-3)/x

f[y]

Mathematica does not know what the following function is, so it simply returns the function as output:

F[y]

Different Bracket Types

This has already been stated, but it is important enough to get its own section!

Square brackets [] are used by Mathematica to define functions, 
round brackets ( ) as delimiters (ie, for multiplication), and 
curly brackets { } for lists.

Here is an example--notice that we have to be careful when doing division and powers to use round brackets to get the expression the way we want it. Notice the difference in the following two functions:

f[x_]=5*x/(x^2+4)+6^(3+x)
g[x_]=5*x/x^2+4+6^3+x

Here is a list of values, which is denoted using curly brackets:

{f[1],f[2],f[3],f[4]}

Built-in Mathematica Functions

Mathematica has a wealth of defined functions, like Cos, Sin, Exp, etc. Generally, a built-in function begins with a capital letter. Since the function is already defined, you do not need to use an underscore if you use it.

Cos[x]

Sin[2]

Tan[3.]

Sqrt[100]

Sqrt[10]

Sqrt[10.]

ArcTan[3.]

The factorial function is defined using the !, which is nice since that is how we write it by hand!

4!

There are many more built-in functions.

Gamma[6]

Zeta[4]

The Exponential Function and Logarithmic Function

One of the most common errors people new to Mathematica make is when they try to use exponential functions. Here is the correct way to input the exponential function g(t)=(e^t):

g[t_]=Exp[t]

g[1.0]

g[Pi]

The following will also work:

g[t_]=E^t

g[1.0]

g[Pi]

What does not work is this:

g[t_]=e^t

g[1.0]

g[Pi]

It looks very similar, but Mathematica treats the e as an undefined constant, not the special constant e ~ 2.71828.

The natural logarithm function, which we usually write as ln, is given by the command Log in Mathematica:

Log[Exp[-45]]

If you want a logarithm with a base other than e, you use another parameter in the Log command:

Log[2,2^3]

Symbolic Calculations

The power of Mathematica is in its ability to do symbolic calculations. We saw that previously when Mathematica reduced 4/6 to 2/3. Mathematica knows the value of Pi:

Pi

Symbolic manipulations are important when working with functions:

f[t_] = Cos[2*t] (t-3)^2

g[t_] = t^2

We can use Mathematica to do compositions of functions, f ◦ g:

f[g[t]]

g[f[t]]

f[f[t]]

Converting Output to a Decimal

If we want a numerical estimate for a symbolic result, we use the command N:

N[Pi]
N[Pi,23]

Another command that will allow you to specify the number of decimals you want to keep is SetPrecision:

SetPrecision[Pi,3]

SetPrecision[Pi,298]

Algebra

Mathematica can help with algebra as well, using commands such as Expand, Factor, Simplify and FullSimplify.

Expand[(a-b)^2]

Whoops! We have forgotten that a has been defined to be 3 in the kernel. We need to clear it first if we wish to use it for something else:

Clear[a]

Expand[(a-b)^2]

Factor[%]

Expand[(a-b)^10]

Factor[%]

Simplify[Expand[(a-b)^10]]

Lists and Tables

Mathematica allows us to create lists and tables easily. Recall that before I said that curly brackets { } are used by Mathematica to denote lists:

datalist1 ={1,2,3,4,5,6,7}

datalist2 = {{1,2},{2,5},{3,16},{4,18},{5,-2}}

The above is a list of ordered pairs. You can think of the ordered pairs as data points, and we will see later how we can plot these points.

Some of the commands we will use in the future include Table, TableForm,

TableForm[datalist1]

TableForm[datalist2]

Plotting

I am including a lot of different types of plots here (scatter, explicit function, implicit function, contour, three dimensional, etc). Do not worry if you do not understand all the different types of plots, as we will be talking more about many of these throughout the semester.

Scatter Plots of Data Points

Let's say we want to plot the data we have in datalist2. We can create a scatter plot of the data in the following manner:

datalist2 = {{1,2},{2,5},{3,16},{4,18},{5,-2}}

ListPlot[datalist2]

Sometimes it is hard to see the points, so we may want to join them

ListPlot[datalist2,Joined->True]

If we have a second data set we want to plot along with the first, we need to label the plots and use the Show command to plot them together.

plot1=ListPlot[datalist2,Joined->True]

datalist3 := {{1,5},{2,17},{4,12},{6,-7},{8,-10}}

plot2=ListPlot[datalist3,Joined->True]

Show[plot1,plot2]

You can click on the image, then clcik and hold on one of the squares at the image edge to resize the image. You could also add an option to specify the image's size when you plot it, and add labels to the axes:

Show[plot1,plot2,ImageSize->{400,Automatic},AxesLabel->{"x","y"}]

You can also add a frame around the image, and label the frame axes:

Show[plot1,plot2,ImageSize->{400,Automatic},Frame->True,FrameLabel->{"x","y"}]

Notice the two lines are both solid. We can change the style of one of the lines (see below), but it does take a bit of work.

Plotting Explicit Functions

To plot explicit functions, the command is slightly different:

f[t_] :=  Cos[2*t] (t-3)^2

Plot[f[t],{t,-5,8}]

If you want to plot more than one function, you need to write the functions you want to plot as a list, so you need to use curly brackets:

plot1 = Plot[{Sin[x] + 2,Sin[x]},{x,-4,4}]

Filled Plots

You can shade the plot using the Filling command. I am also using some commands to make the lines thicker, and add a frame around the plot.

plot1 = Plot[{Sin[x] + 2},{x,-4,4},Frame->True,FrameLabel->{"x","y"},PlotStyle->Thick,Filling->Axis]

plot1 = Plot[{Sin[x] + 2,Sin[x]},{x,-4,4},Frame->True,FrameLabel->{"x","y"},PlotStyle->Thick,Filling->{1}]

Combining Plots

To combine to plots, you can assign each plot to a variable, and then use the Show command.

plot1 = Plot[{Sin[x] + 2},{x,-4,4},Frame->True,FrameLabel->{"x","y"},PlotStyle->{Red,Dashed,Thick}]

plot2 = Plot[{Cos[x] + 2,Cos[x]},{x,-4,4},Frame->True,FrameLabel->{"x","y"},PlotStyle->Thick]

Show[plot1,plot2,PlotRange->{All, All}]

ParametricPlot to plot Parametric Functions

ParametricPlot[{(t^3),(t^2)/(1+(t^2))},{t,-3,3},Frame->True,FrameLabel->{"x","y"},AspectRatio->1,PlotStyle->Thick]

Plots of Implicit Functions

Mathematica plots implicit functions using the ContourPlot command:

ContourPlot[x^4-y^6==Sin[x*y],{x,-2,2},{y,-4,4},PlotPoints->100,ContourStyle->{Red,Thick}]

Plots of Explicit Families of Curves

You should pick values for the constants that provide a good picture of the family of curves. Expect to play around a bit with both the constants and the plot ranges until you get a picture that conveys the family of curves well.

For a family of curves with one constant:

y[t_]=Exp[-2t] + C[1]*((t^2)+1)

functionlist=y[t]/.C[1]->Range[-2,2,0.5]

lines=Plot[Evaluate[functionlist],{t,-2,2},PlotRange->{{-2,2},{-4,4}},AxesLabel->{"t","Family of Curves"},PlotStyle->Red]

For a doubly infinite family of curves:

y[t_]=C[1]Exp[-2t] + C[2]*Exp[-t]+t Sin[t]-1

functionlist=y[t]/.C[1]->Range[-2,2,1]/.C[2]->Range[-2,2,1]

lines=Plot[Evaluate[functionlist],{t,-2,6},PlotRange->{All,{-10,10}},AxesLabel->{"t","Family of Curves"},PlotStyle->Red]

Plots of Implicit Families of Curves

Probably the easiest way to plot a family of curves in Mathematica for an implicit function is to create a list of some members of the family, and then use ContourPlot to plot that list. The Evaluate command is sometimes needed to get the plot, so I included it here.

The Do command creates the list, so adjust the values of c to make sense for your problem (always choose some positive and some negative, since if you choose all positive you might miss interesting members of the family of curves). I have included output of sol so you can see the actual curves being sketched; if it is a long list, supress output using a semicolon. If the list is too long, it will take awhile for the plot to be created.

sol={};
Do[AppendTo[sol,x^2+y^3==c],{c,-2,2,0.5}]
sol

ContourPlot[Evaluate[sol],{x,-5,5},{y,-2,2},ImageSize->{400,Automatic},AspectRatio->0.5,FrameLabel->{"x","y"}]

Notice if you run your mouse over the curves, Mathematica will tell you the equation of each!

You can skip the table and let Mathematica choose the values of c for you, but frankly I prefer to choose my own c values (I feel the sketches are better). Notice that I turn off the contour shading when I do it this way. If you do it this way, Mathematica shows you the value of the contour when you mouse over, not the full equation.

ContourPlot[x^2+y^3,{x,-5,5},{y,-2,2},ImageSize->{400,Automatic},AspectRatio->0.5,FrameLabel->{"x","y"},PlotPoints->200,ContourShading->False]

Contour Plots

You can also create contour plots easily:

ContourPlot[x*Cos[x*y^2],{x,-2Pi,2Pi},{y,0,Pi}]

Adding options to the plot can make it look better. Here, we should use more points to make the plot (this means the plot will take longer to create, of course). You creat the arrow -> by typiing the dash symbol and then the less than sign. Mathematica will automatically join them to make the arrow.

ContourPlot[x*Cos[x*y^2],{x,-2Pi,2Pi},{y,0,Pi},PlotPoints->100]

You can learn more about what options are available for any specific command by typing the following

??ContourPlot

Three Dimensional Plots

You can plot functions of two variables z=f(x,y) using the command Plot3D:

Plot3D[x*Cos[x*y],{x,0,2Pi},{y,0,2Pi}]

You can click on the above object with the mouse and rotate the image to view it from different angles. How cool is that!

Restricting the Domain on Plots Using RegionFunction

Sometimes you may want to plot a curve subject to some constraints. For example, you might want to plot the circle (x^2)+(y^2)=(4^2), but only for the region where -1<x<4 and -2<y<4. Here’s how you can do that. 

Note that the boolean operator AND can be expressed in Mathematica as &&.

ContourPlot[x^2+y^2==4^2,{x,-4,4},{y,-4,4},ContourStyle->{Thick,Blue},RegionFunction->Function[{x,y,z},-1<x<4&&-2<y<4]]

You can even do this where the region is defined by a more complicated inequality.

ContourPlot[x^2+y^2==4^2,{x,-4,4},{y,-4,4},ContourStyle->{Thick,Blue},RegionFunction->Function[{x,y,z},-1<x*y<4]]

This also works with a regular Plot, or a Plot3D. Here we only want to plot the surface above the circle (x^2)+(y^2)≤4.

Plot3D[-x^2-y^2+4^2,{x,-4,4},{y,-4,4},RegionFunction->Function[{x,y,z},(x^2)+(y^2)<4]]

RegionPlot

If you want to show a region that can be done using RegionPlot.

RegionPlot[{x^2+y^2≤9&& x^2<y<10},{x,-5,5},{y,-5,5}]

There is also RegionPlot3D.

RegionPlot3D[x^2+y^3-z^2>0,{x,-5,5},{y,-5,5},{z,-5,5}]

These options allow us to see into the region.

p1=RegionPlot3D[x^2+y^3-z^2>0,{x,-5,5},{y,-5,5},{z,-5,5},PlotStyle->Directive[Yellow,Opacity[0.5]],Mesh->None];
p2=RegionPlot3D[(x-2)^2+(y-2)^2+z^2≤1,{x,-5,5},{y,-5,5},{z,-5,5},PlotStyle->Directive[Red,Opacity[0.5]],Mesh->None,PlotPoints->40];
Show[p1,p2]

Plotting Styles

Here we see some of the ways we can distinguish multiplie functions on a single plot. The PlotStyle option can change the color of the curves, or the thickness of the curve, or both.

Notice that when we plot more than one function, we are plotting a list of functions, so they must be enclosed in curly brackets.

Plot[{x^2,x+1,Log[x]},{x,0,10} ,PlotStyle->{Red,Green,Blue}]

You can let Mathematica choose the color automatically, and make the lines thicker:

Plot[{x^2,x+1,Log[x]},{x,0,10} ,PlotStyle->Thick]

Plot[{x^2,x+1,Log[x]},{x,0,10} ,PlotStyle->{Dotted,Dashed,DotDashed}]

Plot[{x^2,x+1,Log[x]},{x,0,10} ,PlotStyle->{{Dotted,Thick},{Dashed,Thick},{DotDashed,Thick}}]

Solving Equations

Solve

Before we solve an equation, we need to know another form of the "equals" sign used by Mathematica. The Double Equals, ==, is used when defining equations or checking for equality:

3==3

3==4

equation = x^2+2x-1==0

Note that the variable equation is now defined in the kernel:

equation

Solve[equation,x]

The above is a symbolic solver, and we have to give it two parts--the equation we want it to work on, and the variable we want Mathematica to solve for. Let's look at it a little more closely:

quad = a x^2 + b x + c==0

Solve[quad,x]

Solve[quad,b]

Do you understand why the two answers are different?

NSolve

We can tack an N in front of Solve to use Mathematica's numerical solving abilities:

equation = x^2+2x-1==0
NSolve[equation,x]

Here is an example of a Mathematica result which may at first confuse you:

f[x_] = x^3+1x^2+1x
NSolve[f[x]==0,x]

The i in the above refer to the imaginary part of a complex number, and results from taking the square root of a negative number in the quadratic formula that can be used to solve for the roots. Hopefully you will go on to study complex analysis, since it is very interesting and powerful. To interpret the above result, you need to know that the function f[x] has only one real root (as seen from the graph below), and the root is at x=0.

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

Reduce

Another useful solver available in Mathematica is Reduce, which solves equations and includes conditions on the solution, whereas Solve does not include conditions.

Solve[{x==1,x==a},{x}]

Solve tells us there is no solution to these two equations.

Reduce[{x==1,x==a},{x}]

The symbol && means "and", the symbol || means "or"  in Mathematica.

Reduce tells us that there is one solution, if a=1 and x=1.

FindRoot

Another useful solver available in Mathematica is FindRoot, which numerically solves equations and includes an initial guess to the solution which you have to provide. FindRoot can be used when Solve and NSolve fail.

f[x_]=Sin[x]+Exp[x]
Plot[f[x],{x,-4,4}]

FindRoot[Sin[x]+Exp[x],{x,-3}]

FindRoot[Sin[x]+Exp[x],{x,0.5}]

FindRoot also works with systems of equations, and you have to supply guesses for each variable.

FindRoot[{Exp[x-2]==y,y^2==x},{{x,1},{y,1}}]

Manipulate to Create Animations

Manipulate is a wonderful command that produces output as a function of a parameter. It can be used to create animations, among other things.

Plot[Cos[x],{x,0,2Pi},PlotStyle->Thick,PlotRange->{{0,2Pi},{-5,5}}]

We can investigate the behaviour of the function f(x)=cos(a x+b)+c using Manipulate.

Manipulate[Plot[Cos[a*x+b]+c,{x,0,2Pi},PlotStyle->Thick,PlotRange->{{0,2Pi},{-5,5}}],{a,-2,2},{b,0,2Pi},{c,-2,2}]

If you click on the plus sign beside each slider, you can see the value of the parameter that the plot is for. You can use the slider to change the value of the parameter, and even create animations! Try it! Obviously, too many parameters still becomes a bit much if you are doing animations, but certainly this can help you explore the behaviour of fucntions relative to a parameter.

Manipulate also works with things besides plots. Here I tell Manipulate to choose b values from -2 to 2 in steps of 1 (so b=-2,-1,0,1,2):

Manipulate[Reduce[Cos[b*x]==-1,x],{b,-2,2,1}]

Typesetting

You can format your text in Mathematica to be suitable for reports.

The main thing you need to know to get started is how to change the input style. You do this by selecting Format>Style from the drop down menu, or using the shortcut ALT+1 to ALT+7. You can quickly switch between section headings, typed text, and input for the kernel to process.

I usually type the entire document and then decide what style sheet I want. The style sheet will change the look of the entire document, and is like a style file you would use in LATEX. The style sheets are available through Format>Style Sheet drop down menu. Different styles are available for different style sheets; for example, the numbered equation style is not available in the default style sheet, but it is available in the JournalArticle style. Generally the defaul style works fine.

Once you have created your document, you can spell check it by Edit>Check Spelling.

You can export your entire notebook as an html document, pdf, or a LATEX document. This is done through the File>Save As drop down menu. I usually have no problems with the html or pdf output.

Another thing you may be interested in is the File>Print Settings>Show Page Breaks drop down, which will give you some idea of how your document will look when printed. You may choose to change the size of graphs based on page breaks.

There are a wealth of changes and stylizations you can do to your document, but you do not want to fall into the trap of over typesetting your reports! Choose simple, basic commands that make your results easily read, and then leave it at that. For truly great looking formatting, you should use LATEX, since LATEX was designed to typeset equations beautifully and not burden you with the details of marking up your reports.

Derivatives

To check your derivatives that have been computed by hand, there are three main commands you can use.

f[x_]=Cos[x]*Exp[-Sin[x]]

f'[x]
D[f[x],x]
Derivative[1][f][x]

If you want a large order derivative the first form is cumbersome, here is how to get the ninth derivative:

D[f[x],{x,9}]
Derivative[9][f][x]

Notice the results look different, but if we simplify then we see they both give the same function.

D[f[x],{x,9}]//Simplify
Derivative[9][f][x]//Simplify

If we want the derivative evaluated at a point, the third way is the easiest to use.

D[f[x],{x,9}]/.x->Pi
Derivative[9][f][Pi]

Note that the long form Derivative command does require us to define the function first.

f[x_]=Cos[x];
D[f[x],{x,3}]
D[Cos[x],{x,3}]

f[x]=Cos[x];
Derivative[3][f][x]
Derivative[3][Cos[x]][x]

You can get partial derivatives using these commands. For example, here we compute (((∂^2)f)/(∂(x^2)∂y))

f[x_,y_]=Cos[x]*Exp[2y]
D[f[x,y],{x,2},{y,1}]
Derivative[2,1][f][x,y]

Integrals

Definite and indefinite Integrals can be performed with the Integrate command.

Integrate[Log[x],x]

Integrate[Log[x],{x,1,2}]

Integrate[Log[x^a],{x,1,2}]

When Mathematica is Slow or Stops Responding

The Mathematica kernel stores all the information from a given session, even when the notebook is closed and another notebook is opened, until Mathematica itself is closed or the kernel is closed.

One thing you may want to notice is that under Evaluation in the menu there is a command Abort Evaluation. Sometimes this can help you. Sometimes you will need the command Quit Kernel, losing all the information stored in it! Quitting the kernel is therefore a last resort. All your typing will not be lost, but all your data stored in the kernel will be.

It is therefore important to start with a new kernel whenever you begin a Mathematica session, so your calcululations will not be corrupted by information other people have entered into the kernel before you sat down at the computer. By making sure Mathematica is not already running when you start every single time you use Mathematica you will avoid possible confusion later.

Mathematica is pretty fast, but you can slow it down easily if you ask it to do too much. This easily happens with plots.

Plot3D[x*Cos[5x*y]Sin[x^(1+y)],{x,0,2Pi},{y,0,2Pi},Mesh->False]

Adding more points will not make this sketch look better--the function is too oscillatory.

If Mathematica becomes sluggish, look at what you are asking it to do. If it takes a long time to complete a process, you may want to abort the evaluation or even quit the kernel!

Advanced Topic: Curve Fitting

As an example of some of the power of Mathematica, let's fit a curve to some data. What we are going to do is a least squares fit of a polynomial function to the data.

You should know that this is not how I prefer to use Mathematica, and we are doing this only to help you see Mathematica's usefulness. Using Mathematica commands without understanding the math behind them is NOT ONE OF OUR GOALS!! We shall be using Mathematica to help elucidate our understanding of concepts, and help us with things that are difficult to do by hand. We shall not be using it to do our thinking for us.

Clear[data]
data = Table[{i,Exp[i^2/3.]},{i,-2,2,0.1}]

plotdata =ListPlot[data]

f[x_] = Fit[data,{1,x,x^2,x^3},x]

plotmodel =Plot[f[x],{x,-2,2}]

Show[plotdata,plotmodel]