ASEE Introductory Mathematica tutorial
Sept. 23, 2013

Notebook interface, kernel and front end

When you start Mathematica, a blank notebook typically is shown where you can input commands

Opening the program starts the math kernel, which processes commands

The math kernel can also be accessed via command line - this typically isn’t as useful though

4 basic rules for calculations

1)  Capital letters used for all built-in functions:  ListPlot, Plot, Table, Integrate, D, N

2)  [] goes around function inputs:  D[x^2,x]

3)  {} goes around lists:   {1,2,3,4,5}

4)  press shift+enter to run calculations in a notebook

Notebook formatting:  
heading 1:  alt+1

heading 2:  alt+2

heading 3:  alt+3

These can also be set (along with other formatting options) at Format --> Style

Notebook running and accessing output
Note that the commands in the example below won’t correspond to the correct line numbers.  The input and output lines are re-numbered each time the kernel is restarted

The command run last can be accessed with %

4+49

%/2

Any output can be accessed with %<linenumber>.  Use the Out[<linenumber>] above this:

%2

You can also click on an output cell to edit it, or copy/paste results

(53/2)/3

Exact versus numerical calculations

Exact

482894/240204

Sin[45Degree]

Numerical

N[482894/240204]

3* 482940.202390

Sin[45.0Degree]

Everything is a function!

(a+b)/x^2//FullForm

Variable assignment

Set:  rhs is evaluated when the assignment is made, and from then on lhs is replaced by rhs
lhs=rhs

Clear[num,x];  (* Clears values and definitions for these variables *)

x=num

num=5;
x

num=7;
x

x=num;
num=9;
x

FullForm:  Set is a function with shorthand abbreviation “=”

Set[x,3]

x

Clear[x]

SetDelayed:  rhs is maintained in an unevaluated form, and rhs is evaluated each time the value of lhs is requested
lhs:=rhs

num=7;
y:=num

y

num=5;
y

Variables are very general and require no type definition:  they can be numbers, symbols, functions, graphics, lists, plots etc.

michigan=Import["http://geology.com/state-map/maps/michigan-state-map.gif"];
woodencube=;

Polymorphism and lazy evaluation:  Plus, Times, and Sqrt are not defined for those image types - Mathematica leaves the expression unevaluated

num michigan+Sqrt[woodencube]

If statement example:  Matlab vs Mathematica

Compare x and y.  Set val  to 2 times which ever is greater

Imperative style (Matlab).  This IF statement would need to be called each time the values of x and y change

x=3;
y=5;
If[x>y,val=2x,val=2y];

val

Clear[x,y,val];

Functional style.  note the SetDelayed used here to clean it up.

val:=2 If[x>y,x,y];
val

x=49;
y=42;
val

x=1;
val

Clear[x,y,val]

Function definition

Using SetDelayed:
This uses Pattern matching to determine the output when the function is called

func1[x_]:=x^2+x+1;

func1[3]

func1[x+y]

func1[michigan]

Functions of more than one variable

func2[x_,y_]:=x*y;

func2[23,63]

Use pattern matching to change what the function does, depending on how many inputs it has

func2[x];

func2[x_]:=func1[x];

func2[x]
func2[x,y]

Why not to use Set to define functions:
If x is not defined, then the function will work as you expect
If x is already defined, the function will only return a single value

x=4;
sd[x_]:=x^2+x+1;
s[x_]=x^2+x+1;

sd[1]
s[1]

s[8094]

Clear[x]

Pure functions

Define using Function

pure1=Function[x,x^2];
pure1[10]

Shorthand notation:

pure2=((#)^2)&;
more=#1+#2&;
pure2[x]
more[x,y]

List = basic data structure

Create list by entering directly

list1={1,2,3,4,5};

a list can contain all different types of elements

list2={3,x,michigan,Sqrt[woodencube],list1,func1}

Creating lists:  Table

Table[i,{i,1,10}]

Figure out how to change this using Mathematica Help (press F1 with Table highlighted, or search at Help->Documentation Center ):
  --  use Table to create a list of odd numbers from 1 to 50

odds=Table[i,{i,1,50,2}]

Use Table to create a list of ordered pairs:  {x,Sin[x]} from 0 to 4Pi, increments of Pi/10

pairs=Table[{x,N[Sin[x]]},{x,0,4Pi,Pi/10}]

Selecting elements from lists:  Part and Take

I find Part most useful for selecting single elements

Part[pairs,2]

Shorthand:

pairs[[2]]

pairs[[2,1]]

Take is useful for taking ranges, or certain permutations

Take[odds,{3,7}]

Take[odds,3]

Take[odds,{1,-1,2}]

Applying functions to lists:  Map

Use Map to apply a function to each element in the list

Map[Sqrt,odds]

Shorthand notation

Sqrt/@odds

Lists of ordered pairs:  Apply and Map

mult[v1_,v2_]:=v1 v2;
applymult[pair_]:=Apply[mult,pair];

Map[applymult,pairs]

Shorthand for Apply

Apply[mult,pairs[[2]]]

mult@@(pairs[[1]])

And if you’ve followed it all..... the one liner version

#[[1]]#[[2]]&/@Table[{x,N@Sin[x]},{x,0,4Pi,Pi/10}]

Integrals and derivatives

Mathematica  contains a complete database of known integrals, and can be used instead of an integral table

Indefinite integral

Clear[x]

Integrate[x^2,x]

Integrate[Exp[-α (x^2)],x]

Definite integral.  Note that this returns a conditional expression because α is not specified

Integrate[Exp[-a (x^2)],{x,-Infinity,Infinity}]

If we specify the assumption, a conditional expression is not returned

Integrate[Exp[-α (x^2)],{x,-Infinity,Infinity},Assumptions-> Re[α]>0]

Integrate[Exp[-a x^2],{x,-Infinity,Infinity},Assumptions-> Re[a]<0]

Multiple assumptions

Integrate[ Exp[-a x^2],{x,-b,b},Assumptions-> {Re[a]>0,Re[b]>0}]

Derivatives (partial derivatives)

D[Sin[x],x]

D[Sin[x],{x,2}]

func2[x,y]

D[func2[x,y],y]

Derivative operator.  This is most useful for functions of a single variable

Derivative[1][Sin][x]

Common, shorthand use:

Sin'[x]

Take a derivative and evaluate at a specific value, using ReplaceAll

ReplaceAll[D[Sin[x],x],{x->Pi/4}]

Shorthand syntax:

D[Sin[x],x]/.{x->Pi/4}

how NOT to evaluate at a certain value

x=Pi/4
D[Sin[x],x]

Clear[x]

For a single variable function, can use the Derivative operator to evaluate.  The derivative operator can be difficult to use for functions of multiple variables, though

Sin'[Pi/4]

2nd derivative and evaluation

D[Sin[x],{x,2}]/.{x->Pi/4}
Sin''[Pi/4]

Solving equations

Solve an algebraic equation analytically and numerically.  Note the double equal signs (==) for equality

func1[x_]:=1+x+(x^2);

sol=Solve[func1[b]==0,b]
nsol=NSolve[func1[b]==0,b]

Extract these results using the ReplaceAll function

b/.sol

(b/.sol)[[1]]

(b/.nsol)[[1]]

Solve a differential equation analytically.  We’ll use the Derivative operator here for the single variable function

Clear[f,x];

DSolve[f''[x]+a f'[x]+b f[x]==0,f,{x}]

Include initial conditions

DSolve[{f''[x]+a f'[x]+b f[x]==0,f[0]==10,f'[0]==0},f,{x}]

{{f->Function[{x},(1/(Sqrt[(a^2)-4 b]))5 (-a (E^((1/2) (-a-(Sqrt[(a^2)-4 b])) x))+(Sqrt[(a^2)-4 b]) (E^((1/2) (-a-(Sqrt[(a^2)-4 b])) x))+a (E^((1/2) (-a+(Sqrt[(a^2)-4 b])) x))+(Sqrt[(a^2)-4 b]) (E^((1/2) (-a+(Sqrt[(a^2)-4 b])) x)))]}}

Solving numerically requires initial condition(s) and a range, and mult use numerical values

nsol=NDSolve[{f''[x]+ f'[x]+ f[x]==0,f[0]==10,f'[0]==0},f,{x,0,10}]

Evaluate this solution at a certain value

f[2]/.nsol

f[2]/.First[nsol]

A different way:

(f/.First[nsol])[2]

Note Unset is another way to remove a Set definition

f'[0]=10

Clear[f]
f'[0]

Unset[f'[0]]
f'[0]

Plotting

A single function

plot1=Plot[Sin[x],{x,0,4Pi}]

Here, the Evaluate function insures this is going to do what we want

plot2=Plot[Evaluate[f[x]/.nsol],{x,0,10},PlotRange->All]

Multiple functions on a single plot

Plot[{Sin[x],Cos[x],Tan[x]},{x,0,4Pi}]

Plotting numerical data

toplot=Table[{x,Sin[x]},{x,0,4Pi,4Pi/100}];

dataplot=ListPlot[toplot]

Combining plots using Show

Show[plot1,dataplot]

There are lots of options for plots.  The ones I find most useful are PlotRange, AxesLabel, Plotlabel, and Joined (search help to see how to use these)

Options[Plot]

Annotate plots using the drawing toolbox (press ctrl+D or click on Graphics->Drawing Tools to bring up)

plot1

Export a plot as an image

Export["/home/jacob/plot1.pdf",plot1]
Export["/home/jacob/plot1.png",plot1]

Manipulate

Change a single value

Manipulate[a,{a,1,10}]

Manipulate a plot by changing a single value

Manipulate[Plot[Sin[freq x],{x,0,4Pi}],{freq,.1,10}]

Change multiple values and the function being plotted

Manipulate[Plot[amp function[freq x],{x,0,4Pi}],{freq,.1,10},{amp,.1,10},{function,{Sin,Cos,Tan}}]

A complete example:  The harmonic oscillator

First solve it

Clear[f,t]

sol=DSolve[{f''[t]+damping f'[t]+stiffness f[t]==0,f[0]==x0,f'[0]==v0},f,t]

Copy and paste the solution and manipulate the parameters to see how they affect the response

Manipulate[
Plot[ (-2 (E^((1/2) (-damping-(Sqrt[(damping^2)-4 stiffness])) t)) v0+2 (E^((1/2) (-damping+(Sqrt[(damping^2)-4 stiffness])) t)) v0-damping (E^((1/2) (-damping-(Sqrt[(damping^2)-4 stiffness])) t)) x0+damping (E^((1/2) (-damping+(Sqrt[(damping^2)-4 stiffness])) t)) x0+(E^((1/2) (-damping-(Sqrt[(damping^2)-4 stiffness])) t)) (Sqrt[(damping^2)-4 stiffness]) x0+(E^((1/2) (-damping+(Sqrt[(damping^2)-4 stiffness])) t)) (Sqrt[(damping^2)-4 stiffness]) x0)/(2 (Sqrt[(damping^2)-4 stiffness])),{t,0,10}]

,{damping,0,1},{stiffness,1,10},{x0,0,1},{v0,0,1}]

A more complicated example:  Numerically solve using a nonlinear forcing function

Manipulate[
sol=NDSolve[{f''[t]+damping f'[t]+stiffness f[t]==Sin[freq t]^2,f[0]==x0,f'[0]==v0},f,{t,0,finaltime}];
Plot[Evaluate[f[t]/.sol],{t,0,finaltime}]
,{damping,0,1},{stiffness,1,10},{x0,0,1},{v0,0,1},{freq,0,10},{finaltime,10,100}]

Remember to search help (shortcut:  F1) for help with syntax for all built-in functions!