Examples of Useful Stuff

Last modified:  13 August 2012
Please let me know if you find an error....  wraggj@cofc.edu

Getting Started-Numerical Calculations

Just type in a simple mathematical expression, as below, and hit enter.  You will notice that it takes a while for the answer to appear.  That is because the kernel doesn't start until you actually ask it to do something.  Move the input point to any place in the 5+18 below  and push enter to see what I mean.

5+18

Notice also that Mathematica includes a numbered sequence of your input and its output.  If you put the insertion point on the same line again and hit enter it will change to input and output [2].  Try it.

Try some other simple math.  For example raising 3 to the 100th power.  Having entered it and gotten the answer you can easily go back and change the 100 to something else, just like using a word processor.  Change the 100 to 97 and hit enter.  The answer is exact.  Your calculator can't do that.

(3^100)

Mathematica knows a great many things, for example Pi.  If you enter an expression with Pi in it, Mathematica knows that it is the special number Pi.  All special things that Mathematica knows always begin with a CAPITAL letter.  Since Pi is special Mathematica often keeps it in that form when evaluating an expression.  See what entering 2 (times) Pi(squared) does:

2 (Pi^2)

2 (π^2)

You can type π instead of Pi by entering the key sequence "escape-p-escape". 

 If you want a number instead of the symbolic output just enter N[%].  The N means numerical value, the % means the previous output (this saves you from having to retype stuff).  The square brackets are important.  Every  command or function begins with a capital letter and the stuff it operates on is enclosed in square brackets.

N[%]

Mathematica also knows E and I.

(I^2)

(E^1)

N[%]

for higher precision just try N[e^1, 200] to get the value of E to 200 places.  The fancy e symbol (called a double strike e) can be entered by typing "escape-e-e-escape".  The i , used for the square root of -1, is a double-strike i.

N[(E^1),200]

Some other useful things that Mathematica already knows:  Sqrt, Sin, Cos, Tan, Integrate....

N[(Sqrt[π+E+Sin[2 π+1]]),50]

Complex numbers are no problem at all

(((3+2 I))^3)

Graphics

Simple 2-D and 3-D Plots

Mathematica can plot two or three dimensional plots easily.  Observe that Exp[x] means the same as (E^x)and as (e^x).  Lists are always enclosed in curly brackets {}, with each item separated by a comma.  See the list in the following Plot command, in which we specify what variable we are plotting and over what range.

Plot[Sin[(E^x)],{x,0,π}]

Almost every command you can give Mathematica has options.  Here we plot two different functions on the same graph.  Options are handled in a very consistent way. Notice in the plot below how Mathematica automatically colors the two different curves.

Plot[{Sin[(E^x)],(1/x)},{x,0,π},Frame->True,PlotLabel->"Signal"]

To get help or information on things go to the “Help” menu and select “Documentation Center”.  Or, just use two quextion marks and the thing you want to know about

??PlotRange

In the plot below the gridlines are used to help visualize the shape.  The actual resolution is dictated by "PlotPoints" which specifies how many points of the function are sampled in each direction, so the total number of values of the function is the value of PlotPoints squared.

Plot3D[Sin[x+Sin[y]],{x,-4,4},{y,-4,4},PlotPoints->50, PlotRange->{-1.5,1.3}]

Change the number after PlotPoints and hit enter to see what happens.  Try a smaller number and larger numbers.

Handy Tricks with Plots

Here is a sample plot which incorporates several features that might come in handy.  Try messing with the options, but only change one thing at a time unless you are very confident in what you are doing.

Plot[Sin[(x^2)],{x,0,6},Frame->True,FrameLabel->{"Time (s)","Velocity (m/s)"},RotateLabel->True,PlotStyle->RGBColor[1,0,0],PlotRange->{-1.5,1.5},PlotRegion->{{0.1,0.9},{0.1,0.9}},AspectRatio->Automatic,Epilog->{RGBColor[1,0,1],Text[Sin[(x^2)],{0.7,-0.8}],RGBColor[1,0,1],Disk[{2.8,1},0.15]}]

Piecewise Plotting, and Ticks

Plot[(Piecewise[{{Sin[x], x<0}, {(x/3), x>0}}]),{x,-π,1}]

Plot[(Piecewise[{{Sin[x], x<0}, {(x/3), x>0}}]),{x,-π,2},Ticks->{{-π,-(π/2),0,(π/2)},Automatic}]

A Simple animation

Double-click on the graph below.

λ=.3;
f=4;
Animate[Plot[Sin[(((2 π) x)/λ)-(2 π f) t],{x,0,1}],{t,0,1}]

More Animated Plots

Animated plots are done by making multiple graphs and displaying them in rapid sequence.  Usually one mechanizes the process of making multiple plots using the "Do" command.  Double click on one of the plots in the series and it will animate the sequence.

Animate[Plot3D[((Cos[(Sqrt[(x^2)+(y^2)])+Abs[n-2 π]])/(Sqrt[(x^2)+(y^2)+(1/4)])),{x,-4 π,4 π},{y,-4 π,4 π},PlotPoints->26,Lighting->Automatic,PlotRange->{-2,2},BoxRatios->{1,1,1},Boxed->False,Axes->None],{n,0,2 π-((2 π)/16),((2 π)/16)}]

Simple Algebra and Calculus

9 (((2+x))^3) (x+y)+(((x+y))^2)

Expand[%]

Factor[%]

Mathematica can do indefinite, definite, and numerical integration

∫(x^2)\[DifferentialD]x

∫(((x^2)+1)/(x-1))\[DifferentialD]x

∫(x^2) ((Sin[x])^2)\[DifferentialD]x

Derivatives too!  The % symbol refers to the previous output.  Here we take the derivative with respect to x (d/dx) of the previous output

(∂_x)%

But this doesn't look like the original integral, does it?  Let's simplify it.

Simplify[%]

Here is a definite integral.  Note how easily the limits of integration are put in.

(∫_0^(2 π))(x^2) Sin[x]\[DifferentialD]x

(∫_0^∞)(x^2) (E^(-x))\[DifferentialD]x

Expressions can be numerically integrated.  This is especially useful for cases where the integrand cannot be integrated by traditional methods.

NIntegrate[x (E^(-x)),{x,0,π}]

Reading a File from Excel & Plotting Data

Note:  I saved an Excel  spreadsheet  using the file name "test_math.xls".  The spreadsheet consisted of two columns, one of the integers from 1 to 10, the second column was their squares.  The saved file was on the Desktop.  First I must tell Mathematica where to look for the file...

SetDirectory["/Users/jeff/Desktop"]

data2=Import["test_math.xls"]

Note the extra set of braces around the list.  It doesn't seem to cause a problem, but you can make them go away using the "Flatten" command - Flatten[data2,1].

ListPlot[data2,AxesOrigin->{0,0},Frame->True]

Plotting and Fitting Data

Fit a function to a table of {x,y} pairs

If you have some data you can plot it and fit it to curves.   The data can be read in from some outside file as in an above example, or can be entered by hand. First make a simple data set, then plot it, illustrating some standard options for a plot, which you could figure out if you tried.  Put together a simple plot and play with the options.  Some options are mutually exclusive I think.  For example, "FrameLable" doesn't print anything unless "Frame" is True.

smart={{405,1.541},{435,1.536},{546,1.531},
	{579,1.527},{615,1.525},{734,1.524}};

smartplot=ListPlot[smart,AxesOrigin->{400,1.522`},AxesLabel->{"xx (s)","yyy (m)"},Frame->False,FrameLabel->"My Cool Plot  ",RotateLabel->False,PlotLabel->"Plotlabel",PlotStyle->{PointSize[0.02`],RGBColor[1,0,0]}]

Now the "Fit" command is used to fit the data to a constant plus a (1/(x^2))term

smartfit=Fit[smart,{1,(1/(x^2))},x]

smartfitplot=Plot[smartfit,{x,400,750},AxesOrigin->{400,1.522}]

Show[smartplot,smartfitplot]

Non-linear fitting

theData={{-3,0.1},{-2.5,0.2},{-2,0.28},{-1.5,0.4},{-1,0.7},{-0.5,1.5},{0,3},{0.5,4.6},{1,5.1},{1.5,4.7},{2,2.94},{2.5,1.52},{3,0.72},{3.5,0.37}, {4.5,0.22}};

MatrixForm[theData]

dataPlot=ListPlot[theData,PlotStyle->PointSize[0.02]]

Now define the function you want to fit (in this case a translated gaussian) and determine the fit parameters (in this case, the constants, a,  b, c).

fitFunction=a (E^(-b (((x+c))^2)))/.FindFit[theData,a (E^(-b (((x+c))^2))),{a,b,c},x]

Plot the fit function you just determined

fitPlot=Plot[fitFunction,{x,-5,5}]

Now plot the fit function and the data, so you can see how good (or bad) the fit is.

Show[dataPlot,fitPlot]

Or this works too...

Plot[fitFunction,{x,-5,5},Epilog->Point/@theData]

Making, Altering, and Plotting Tables

The basics, with a plot example

The "Table" command has the form:  Table[expression, {i, imin, imax, di}].
It generates multiple copies of "expression" using values of i from imin to imax in steps of di.  Table[expr, {i, imin, imax}, {j, jmin, jmax}, ... ] gives a nested list.

table1=Table[Sin[n x],{n,1,3,1/2}]

Individual elements of a simple table can be referred to like this:

table1[[3]]

Tables can also be entered directly using { } and separating elements with commas.

tablestuff={-x^2,-100,-144}

Plot[Evaluate[tablestuff,{x,-12,10},Axes->False,PlotStyle->{{Thickness[0.003]},{Dashing[{0.03}],Thickness[0.003]},{Dashing[{0.01}],Thickness[0.003]}}],Prolog->{Circle[{0,0},{0.15,1.5}],Circle[{-12,-144},{0.15,1.5}],Circle[{-7,-49},{0.15,1.5}],Circle[{7,-49},{0.15,1.5}],Circle[{10,-100},{0.15,1.5}]},AspectRatio->1]

Manipulating Data Tables

First define a simple table.  You are going to want to manipulate individual columns of this data.

rawdata=(({{15, 465}, {30, 423}, {45, 399}}));

a simple command "Length[ ]" returns the length of a table, which is useful later.  This is to save you the trouble of counting the number of data points you have.

Length[rawdata]

Now do the background correction by subtracting a constant from the second column,, assuming your background is 5 counts/second,

correcteddata=Table[   {rawdata[[n,1]],rawdata[[n,2]]-5}  ,{n,1,Length[rawdata]}]

You can always display this in prettier form by

MatrixForm[%]

Now take a natural log of only the second column, and make the result a decimal number.  the final result is the data you use to do the line fit.  Of course if you don't do the line fit, but rather fit the correcteddata table above to an exponential, you won't need this step.

logtable=MatrixForm[Table[   {correcteddata[[n,1]],N[Log[correcteddata[[n,2]]]]}  ,{n,1,Length[rawdata]}]]

Build a simple table of functions, and plot them

thingy=m x;

thingytable=Table[thingy,{m,1,10}]

Plot[Evaluate[thingytable],{x,0,5}]

Expanding a Function into a Series...

Here is a way to approximate an ugly function as a sum of nice functions....  It uses the built-in Mathematica function "Series" which makes it a power series in the specified variable (here it is x), valid around the specified point (here it is around zero), up to terms with the specified power (here it is 8).  Then I extract (by cut/paste) each piece of the series expansion and I can plot them individually or add them up and show how well they fit the original function.

uglyfunction=Sin[(Sqrt[(x^2)+1])];

Series[uglyfunction,{x,0,8}]

piece1=Sin[1];
piece2=(1/2) Cos[1] (x^2);
piece3=(-((Cos[1])/8)-((Sin[1])/8)) (x^4);
piece4=(((Cos[1])/24)+((Sin[1])/16)) (x^6);
piece5=(-((3 Cos[1])/128)-((7 Sin[1])/192)) (x^8);

Plot[{uglyfunction,piece1+piece2+piece3+piece4},{x,-1,1},PlotStyle->{RGBColor[0,0,0],RGBColor[0,0,1]}]

Solving  Equations

Solve-a couple of examples

First a simple example of a single equation, and the Solve command, all in the same cell.  To solve equations, just remember that an equation has to be written with a double equals sign, == .

ourEqn=3 (x^2)-x==0;
Solve[ourEqn,x]

Now something every so slightly more interesting.  Note that there are two variables, x and a.  So we will solve this equation for x

(x^3)-7 (x^2)+3 a x==0;
Solve[%,x]

Numerical solutions are easy too, since there are some equations which can't be solved in an algebraic way (although the first one can be).

NSolve[(x^3)-7 (x^2)+3 x==0,x]

That one was easy.  Now here's an example of a transcendental equation, which cannot be solved by algebraic techniques.  The approach is to rearrange the equation such that the algebraic part is on one side of the == and the trigonometric is on the other.  Plot them and see where they cross (i.e., where they are equal).  Then use FindRoot to get the answer.  With the plot you can just keep narrowing down the range of x values to close in on the crossing point.

anotherEqn=x + Tan[x]==5;
Solve[anotherEqn,x]

Plot[{5-x,Tan[x]},{x,0,2 π},PlotRange->{0,6}]

FindRoot[anotherEqn,{x,1}]

Extracting the answers to "Solve"

Note that the output of the Solve command is a list, or a rule for the solutions.  This makes it somewhat awkward to use the solutions in further calculations.  Below is an illustration of the fairly non-intuitive way to get the solutions in a useful form for further manipulation.   First we name the list that forms the solutions to our equation.  then we extract the solutions and name them sol01 and sol02 so we can refer to them.

sol = Solve[x^2 - 6*x - 16 == 0, x]
sol01 = sol[[1,1,2]]
sol02 = sol[[2,1,2]]

Solving Differential Equations...

DSolve[eqn, y, x] solves a differential equation for the function y, with independent variable x.  Here we see an example of our very first differential equation in Modern Physics.  This one is from the Particle in a Box problem.  C[2] and C[1] are just constants we don't care about since we have to normalize the wave function anyway.

DSolve[ψ''[x]==-(a^2) ψ[x],ψ[x],x]

For the particle in a finite square well, in the forbidden region, we have...

DSolve[ψ''[x]==(a^2) ψ[x],ψ[x],x]

Also note that:
DSolve can solve a list of differential equations. 
DSolve can solve a partial differential equation. 
NDSolve[eqns, y, {x, xmin, xmax}] finds a numerical solution to the ordinary differential equations.  This is a particularly useful command.

Vector Calculus:  Grad, Curl...

Not every thing Mathematica can do loads when you start it.  Much functionality is in supplemental packages you have to load using the commands shown below...

<<"VectorAnalysis`"

CoordinateSystem[]

Coordinates[]

Grad[(x^2)+(y^2)+z, Cartesian[x,y,z]]

Curl[{2 z  (y^2) ,x y,x z}, Cartesian[x,y,z]]

VectorPlot[{y,-x},{x,-3,3},{y,-3,3}]

VectorPlot3D[{z  y ,x y,x z},{x,0,5},{y,0,5},{z,-2,3}]

Other Plotting: Polar, Surface of Revolution, etc.

Polar Plots

PolarPlot[{(4/(2+Cos[θ])),4 Cos[θ]-2},{θ,0,2 π}]

Here is an ellipse in polar coordinates.  You must have 0< e <1

e=0.9;
ellipse=(e/(1-e Cos[θ]));
PolarPlot[ellipse,{θ,0,2 π}]

Surface of Revolution

A surface of revolution is generated by rotating a curve about a given line. SurfaceOfRevolution plots the surface of revolution generated by rotating about any axis the graph of a function in the x-z plane or a curve described parametrically.

RevolutionPlot3D[Sin[x],{x,0,2 π}]

Now some other stuff, 3D point plots

testdata={{1,1,1},{1,2,1},{-1,-2,0},{1,-1,3},{0,0,0}};ListPointPlot3D[testdata,SphericalRegion->False,Boxed->True]

Graphics3D[{Blue,Sphere[{2,2,2},0.3],
Red,Cylinder[{{0,0,0}{1,1,1}},0.3],
Orange,Dashed, Thick, Line[{{-2, 0, 2}, {2, 0, 2}}]}
]

Sound

Mathematica can render mathematical expressions into sound.  The command is"Play" as illustrated below.  Note that arguments for trig functions are radians, if you  input Hertz you must multiply by 2π.

Play[Sin[440 2 π t],{t,0,2}]

<<Music`

MusicScale[JustMajor,220,1.5]

See if you can figure out the syntax here...

MusicScale[{100,950,350,1200},880,1]

Making your Own Function

There are several styles of programming in Mathematica.  One of them is procedural programming, as you would find in a standard structured programming language such as C or Pascal.

Another is “rule-based programming”.  The idea is to give transformation rules which specify how Mathematica  should transform expressions it receives as input. 

You can give rules that mimic the formulas you might find in a mathematics textbook.

Here is an example of how you might teach Mathematica  about a new form of logarithm function, called dogleg.

Mathematica  initially knows nothing about our new function, so it does nothing to expressions involving dogleg.  Here is how we tell Mathematica  how to expand out dogleg of products.

dogleg[x_ y_] := dogleg[x] + dogleg[y]

dogleg[a b c d^2]

Now Mathematica  can expand the dogleg out. Now lets define a rule for dogleg of a power.

dogleg[x_^n_] := n dogleg[x]

dogleg[a b c d^2]

Now Mathematica  can expand the expression out completely.

Another style of programming you can use in Mathematica  is functional programming.  In functional programming, you specify a collection of functions to apply.  This style of programming often yields compact, elegant programs that make good use of Mathematica's many integrated capabilities.

This is a program that plots the solutions to a polynomial equation as points in the complex plane.

RootPlot[poly_, z] :=
  ListPlot[{Re[z], Im[z]} /. NSolve[ poly == 0, z], AspectRatio -> Automatic ]

You can immediately use the program to plot solutions.

RootPlot[ z^7 - 1 , z]

Handy but Strange Functions -  Step Function, DiracDelta

The example, which would be useful to those doing elementary quantum mechanics as well as other problems, combines two unit step functions to form a "Square well".

??UnitStep

Plot[0.3+(-UnitStep[x]+UnitStep[x-1]),{x,-4,4}, Axes->True, PlotRange->{-1,1}]

??DiracDelta

Real and Floating Point Numbers

Real Numbers

You can make sure Mathematica only considers real numbers in some contexts by loading the package "RealOnly"
     <<Miscellaneous`RealOnly`
 
 Miscellaneous`RealOnly` was available as an add-on package in previous versions of Mathematica and is now available on the web at library.wolfram.com/infocenter/MathSource/6771.

Floating Point Numbers

You can tell Mathematica to convert all expression to their numerical (floating point) value for a session ...

3/5

$Pre=N;

{3/5, Pi}

Just remember, once you do this, it remains in effect for the session, even if you erase it.

17/45