Introduction to Mathematica

Julius, EIMI

Lecture 1 - based on lectures by (N. Gromov, King’s College London and J.Harris, Wolfram Research)

Mathematica is a symbolic programming language that has become ubiquitous in many areas of mathematical and physical research. This course is an introduction to the language. No prior programming experience is assumed.

Basics

Commands are implemented line-by-line in Mathematica, one can implement a line of code, by pressing the “shift” key and the “enter” or “return” key simultaneously. One set of lines which get implemented together is called a “cell”. You can see the input and output numbers on the left of any cell. You can select the contents of a cell by hovering your cursor to the right of the cell. Once selected you can evaluate it with “shift” + “enter”. You can select multiple cells and evaluate them together - they will evaluate in the order of the cells in your Mathematica notebook. When a cell evaluates, you will see that the right border of the cell becomes black and bold, this goes back they grey line that it was after the cell evaluates.

(*excecute using "shift" + "enter"*)
2 + 3

(*excecute using "shift" + "enter"*)
2  3

(*type "Cnrl" + "/"*)
(\[Placeholder]/\[Placeholder])

(222/3)

(*type "Ctrl" + "2"*)
(Sqrt[\[Placeholder]])

(Sqrt[144])

Go to the “Palettes” menu and open the “Basic Math Assistant”. Use it to type the following expressions:

(a^(2 ))+ (b^2)
(Sqrt[α + 𝕚 β])
(({{-1, 0}, {0, 1}}))
(∑_(n=1)^∞)(1/(n^2))

(*Evaluate the last expression*)
(∑_(n=1)^∞)(1/(n^2))

You can hover over the cells in the Basic Math Assistant and see that there are keyboard shortcuts for the same expressions. Type the following expressions using only keyboard shortcuts:

(12^(Sqrt[15129]))
(({{1, 4}, {2, 1}}))
(Sqrt[1 + (x/3)])

Important: sometimes if you run a cell which triggers an infinite-loop, then you need to abort the evaluation, there are three ways to do this. Firstly, one can go to the “Evaluation” menu and click on “Abort Evaluation”. This should make the bold black line which shows the evaluation of the infinite-loop, go back to normal and print an “$Aborted” message below. For example, evaluate the following expression which triggers an infinite loop, and then abort it:

1 + F[x]//.F[a_]->F[F[a]]

There is also a keyboard command to abort evaluation, which is usually “Cmd”/”Alt” + “.”. In some cases, one needs to kill the entire kernel and clear all variables, this is done by going to the “Evaluation” menu, then clicking “Quit Kernel” and selecting “Local”.

Assignments, Functions, OutputForms and Special Variables

Variables are assigned using “=”. For example

a = 2;
b = 3;

a+b

a b

You can clear a variable by using the function “Clear” or my using the assignment “=.”

a =.
b=.

a+b

a b

Notice that unassigned variables are blue, whereas assigned variables are black and that a variable goes from black to blue once cleared. Another thing is that the “;” symbol can be used to suppress the output if you so desire.

Functions are applied to arguments by placing the arguments within square brackets. For example

f[a+b]

Factorial[5]

Notice that square brackets are special, if you use parenthesis, then you will cause a multiplication or an error:

f(a + b)

Factorial(5)

There are two type of output forms: “StandardForm” and “TraditionalForm”. StandardFrom is by default, but sometimes TraditionalForm can be better. Both have their advantages and disadvantages, and it a matter of personal taste which you prefer.

(({{1, 2}, {3, 4}}))

(*One case where traditional form can be better is that it shows matrixes as matrices rather than nested lists*)
TraditionalForm[(({{1, 2}, {3, 4}}))]

(*However this can be achieved also using MatrixForm*)
MatrixForm[(({{1, 2}, {3, 4}}))]

BesselI[1,z]
TraditionalForm[BesselI[1,z]]

The advantage of StandardForm is that you can copy the output of a cell, and use it as a new input, in TraditionalForm, this might not always work.

f[a+b]

TraditionalForm[f[a+b]]

(*For example, this works superfecially *)
f(a+b)

(*But if you add a space between f and (a +b), then it gets interpreted as a product *)

f (a+b)

(*Not the case for StandardForm*)
f      [a + b]

Some variables have fixed values like:

N[{Pi,π, E, I,Infinity,∞}]

Lists

Lists in Mathematica, are generalised versions of vectors and matrices, and are very important.

(*Define a list with curly brackets*)
list = {1,12,3,22}

(*Equivalently, we can write*)
list  = List[1,12,3,22]

Notice that default functions in Mathematica always begin with a capital letter, and if you try to use one of the default function names for assignment, you will return an error message:

List = {1,12,3,22}

Later in this course we will see how to tell Mathematica to “forget” about defaults for some particular symbols.

You can access a member of a list using double square brackets, or the “Part” function.

list[[2]]

You can also reassign this element:

list
list[[2]]=22;
list

Part can be applied to functions as well, and in a nested fashion:

f[a,b[x ,y + α],c,d]

f[a,b[x ,y + α],c,d][[2]][[2]][[1]]

f[a,b[x ,y + α],c,d][[2,2,1]]

There are more functions like “Take” and “Drop” which allow you to select subexpressions of an expression:

Take[f[a,b,c,d,e],-3]

f[a,b,c,d,e][[-3;;]]

Drop[f[a,b,c,d,e],2]

Matrices are two-dimensional lists. They can be defined using nested lists for example, or using some shortcuts:

mat = {{1,2},{3,4}}
mat = (({{1, 2}, {3, 4}}))
MatrixForm[mat]

Operations on matrices like taking the determinant, trace or multiplying them, can also be done:

Det[mat]

Tr[mat]

MatrixForm[mat.mat]

MatrixForm[mat mat]

Notice that there are two different ways to multiply matrices, so one should be careful about which type of multiplication they would like to implement.

The function “Table” can be used to make a list, for example

tab = Table[i^2,{i,1,100}]

(*You can see more options for Table here, in gneral "?" follwed by the name of a function gives you more information about it.*)
?Table

Table[i^2,{i,1,11,2}]

Table[i^2,{i,11,1,-2}]

(*Suppose you don't know what the function name is, but you suspect that you may know a part of the name, then you can try*)
?*Sin*

MatrixForm[Table[(Subscript[m, i,j]),{i,4},{j,4}]]

Problem 1: Obtain the following matrix using Table

Delayed assignment, replacement, and function application

So far we saw how to make an assignment of a variable, however there are more subtle ways to do this as well. This is using delayed assignment. Let us illustrate:

?Random

x = Random[];
y := Random[];

(*you can also check what is stored in a variable using ?*)
?x
?y

Table[x,{i,10}]
Table[y,{i,10}]

There are different syntaxes that one can use to apply functions

x=.

f@g@h@x==f[g[h[x]]]

(*The symbol "==" is used to check if two expressions are equal and returns the Boolean variable "True" or "False"*)
(*The "%" sign is used to print the most recent output, Repeating it n times will print the output of the (n^th) most recent output*)

x//h//g//f
f[g[h[x]]]
%%==%

“Map” is a function that can be used to map a function to a list or more generally an expression:

Map[foo,bar[a,b,c,d]]

It has the short form “/@”

foo/@{a,b,c,d}

bar/@foo/@{a,b,c,d}

bar[foo/@{a,b,c,d}]

bar@@foo/@{a,b,c,d}

bar@@@(foo/@{a,b,c,d})

Similar to assignments, functions and replacement rules can also be defined in two ways. Let us start with substitution rules. Similar to the assignment, we can do

sbx1 = x-> Random[];
sbx2 = x:>Random[];

Table[x/.sbx1,{i,10}]
Table[x/.sbx2,{i,10}]

Table[x/.x->Random[],{i,10}]
Table[x/.x:>Random[],{i,10}]

The syntax to define a function is the following. One can use both delayed assignment as well as direct assignment. In some cases, practically there is no difference

MySquare1[x_]:=(x^2)
MySquare2[x_]=(x^2);

MySquare1[178]
MySquare2[178]

While in other cases, there could be a big issue, run the next cell and try to understand the error message.

Clear[fac]
fac[n_]=n fac[n-1]
fac[0]=1;

This is why we prefer to use delayed assignment in some cases.

Clear[fac]
fac[n_]:=n fac[n-1]
fac[0]=1;

fac[5]

fac[6]

Our program is still not perfect, it tries, and fails, to compute the factorial of numbers outside the domain of definition of the function. We will tackle this in a subsequent problem.

fac[-2]

Problem 2: Write a recursive program for Fibonacci sequence. Is there a way to make it faster while still recursive?

Clear[fib]
fib[n_]:=fib[n-1] + fib[n-2];
fib[1] = 1;
fib[0]=0;

fib[20]//Timing
fib[30]//Timing
fib[20]//Timing

Optimisation

The trick here is to save to the memory, all previous computations of the Fibonacci numbers.

Clear[fib]
fib[n_]:=fib[n]=fib[n-1] + fib[n-2];
fib[1] = 1;
fib[0]=0;

As you can see, this way is much faster! Furthermore, even the first computation of the fib[20] is much faster than before, even when it is evaluated the first time, because many of the repeated Fibonacci numbers which occur in the recursive tree to compute fib[20] are already saved to memory when they appear for the first time in this tree.

fib[20]//Timing
fib[30]//Timing
fib[20]//Timing

Problem 3: Improve the factorial code so that it go into an infinite recursion if the argument is not a non-negative integer

Clear[fac]
fac[n_Integer/;n>0]:=n fac[n-1]
fac[0]=1;

fac[-2]

fac[3/2]

A pattern of the form var_h will only match the expressions whose “Head” is h

Head@2

Head@-2

Head@(3/2)

Head@{1,2,3,4}

fLs[x_List]:=x;

fLs[{x}]

pat /;  expression will only evaluate if expression is true

Problem 4: Write a function which squares odd integers and cubes even integers

Explore other query functions, which have the letter “Q” at the end of the function name.

OddEven[n_Integer?OddQ]:= n^2
OddEven[n_Integer?EvenQ]:= n^3

OddEven[3]
OddEven[2]

Mathematica as a calculator

Problem 5: Integration

5.0. Type “?Integrate” to see the usage.

5.1. Evaluate ∫ x Sin[x] dx.

5.2. Evaluate ∫((x^5)/(Sqrt[1 + (x^2)]))dx.

5.3. Evaluate∫(((x^5)(y^5))/(1 + (x^2)))dx dy.

5.4. Evaluate (Subscript[(∫^(+∞)), -∞]) (e^(-(x^2)))(x^10)dx.

5.5. Evaluate (Subscript[(∫^(+∞)), -∞]) (e^(-a (x^2)))(x^2)dx, will need “Assumptions” option.

Problem 6: Differentiation

6.0. Type “?D” to see how to use this function.

6.1. Compute ((d^2)/(d (x^2)))(Sin^2)[x], simplify it using “Simplify”.

6.2. Compute ((d^5)/(d (t^5)))Sin[Cos[t]], simplify it using “Simplify” it, and evaluate it at t = π/2 and t = π/3 by using replacements of the form (* /. t-> π/2*) to the right of your expression.

6.3. Compute ((d^4)/(dx (dy^3)))Sin[(x^2) + y] and evaluate it at x = (Sqrt[π/3]) and y = 0.

Problem 7: Taylor Series

7.1. Use the “Series” function to expand (e^x) up to the (x^(10 ))term.

7.2. Expand Sin[Cos[x]] in a Taylor series about x = π.

Problem 8: Limits

8.1. Find (lim_(x->0)) ((Sin[2 x])/x)

8.2. Plot ((Sin[x])/(|x|)), use the “Direction” option of the limit to compute (lim_(x-> 0- ))((Sin[x])/(|x|))

Problem 9: Manipulating symbolic expressions

expr1 = (1/(x+1))+(1/(x+2))+(1/(x+3));

7.1 Use “Factor” to see how it works

7.2 Apply “Apart” on the Factored expression and see if you can restore the partial fractions.

x=.
y=.

expr2 = (1 + x + y)^5;

7.3 “Expand” it

7.4 “Collect” in terms of powers of a variable.

Problem 10: Solving equations

10.1. “Solve” the single non-linear equation: (x^3) + 2 (x^2) + 2 x + 1 == 0

10.2. Solve the system of equations: (x^2) + x + y ==0 and (y^2) + y + x == 0

10.3. Use “DSolve” to solve: y’’[x] + y[x] + Exp[x] == 0

Try to do the following two problems yourself before opening the solution, by double clicking on the right end of the cell

Problem 11: Compute the volume of the shape defined by the conditions (x^2)+(y^2)<1 and (x^2)+ (z^2) < 1 and plot it

?Boole

Integrate[Boole[x^2 + y^2<1&&x^2 + z^2 <1],{x,-1,1},{y,-1,1},{z,-1,1}]

?RegionPlot3D

RegionPlot3D[x^2 + y^2<1&&x^2 + z^2 <1,{x,-1,1},{y,-1,1},{z,-1,1}]

Try problem 11 below this cell

Problem 12: Use “ContourPlot3D” to plot the separately the hyperboloids "
(x^2) - (y^2) - (z^2)  == -1” and "
(x^2) - (y^2) - (z^2) == +1”. Use “Manipulate” to make a single dynamic plot to go from one to the other.

?ContourPlot3D

ContourPlot3D[x^2 - y^2 - z^2 ==-1,{x,-2,2},{y,-2,2},{z,-2,2}]

ContourPlot3D[x^2 - y^2 - z^2 ==+1,{x,-2,2},{y,-2,2},{z,-2,2}]

?Manipulate

Clear[CP]
CP[u_]:=ContourPlot3D[x^2 - y^2 - z^2 ==u,{x,-2,2},{y,-2,2},{z,-2,2}];

Manipulate[CP[u],{u,-1,1}]

Try problem 12 below this cell