Scientific & Engineering Programming

Lecture I

Mathematica basics

Robert Muszyński

Department of Cybernetics and Robotics
Wrocław University of Science and Technology

Copyright 2017 RM

How to start and quit

User front-ends

terminal (command: math)

graphical (command: mathematica or by icon)

Expression input and computation

type in an expression and use the enter key to compute

in graphical when ready use the shift + enter keys to compute

To terminate

use Quit function (in the terminal mode)

use Menu (in the graphical interface)

Need help

type ? (or even ??) and the term you are looking for

?Sin

in graphical mode use Help menu :)

Do not run multiple Mathematica instances if not necessary

observe that double clicking the Mathematica file icon, or opening a file directly from a web page, brings typically a Mathematica interface which is a new instance of it (with a separete MathKernel and one licence taken) - if it is not your intention use File -> Open menu option instead

Numerical calculations

Arithmetic

Exact versus approximate, any precision

2+2                    (* Exact *)
2+2.                  (* Approximate *)
N[2+2]
2+2//N

2^100                 (* Exact *)
2^100//N       (* Approximate *)

1/3+2/7                          (* Exact - rational numbers *)
%+0.000000000000001 (* Approximate - numerical value *)
1/3+2/7//N

Pi                       (* Exact *)
Pi//N             (* Approximate *)
N[Pi]
N[Pi,300]

x+y+z	x-y-z		x*y*z		x y z		x/y/z	-x

N[expr]	expr//N		N[expr,acc]

Math functions

Give arguments in brackets [], start built-in functions with a capital letter

Sin[1]          (* Exact *)
Sin[1.]        (* Approximate *)
Sin[Pi]
Sin[Pi/3]

Sin[Pi/5]      
Sin[Pi/13]

Sin[30 Degree]
Tan[Pi/2]

Sqrt[16]             (* Exact *)
Sqrt[2]               (* Exact *)
Sqrt[2]//N      (* Approximate *)
Sqrt[-1]

Sqrt[x] 	Exp[x]		Log[x]		Log[b, x]
 Sin[x]		Cos[x]		Tan[x]		Cot[x]
 ArcSin[x]	ArcCos[x]	ArcTan[x]	ArcCot[x]
 n!			Abs[x]		Round[x]	Mod[n, m]

Computational techniques

Recalling the results

Use percent sign

2+1
2+2
2+3
%
%%%
%
%5

% - last			  %%...% (k-times) - kth before last
 %% - last but one	  %n - nth

Use variables (the next slide:)

Variables

Use  =  or   :=   operators

x=5          (* set immediately *)
y:=5        (* set delayed *)
x^2
y^2

a=4;
x=5+a;
y:=5+a;

; - do not display results

x
y

a=7;
x
y

x=.        (* clear value *)
x
y

= - Set[]	:= - SetDelayed[]	x = . - Clear[x]

Lists

Compose with braces {}, take parts with double brackets [[]]

{3,5,1}
{3,5,1}^2+1
{6,7,8}-{3.5,3,2.5}
{6,7,8,9}-{3.5,3,2.5}

Exp[%%]
%//N

v={2,4,3.1}
v/(v-1)

{5,8,6,9}[[2]]
{5,8,6,9}[[{3,1,3,2,4}]]

v={2,4,7}
v[[2]]

v[[2]]=1
v

Mathematica’s bracketology

f[x] 		- brackets for arguments of functions
 {a,b,c} 	- braces for lists
 v[[i]] 	- double brackest for indexing
 (term)		- parentheses for grouping

Four kinds of “brackets”

f[x,y]		- prefix notion
 x~f~y		- infix notion
 x//f		- postfix notion

Three types of function notions

(Subscript[expr, 1]); (Subscript[expr, 2]); (Subscript[expr, 3])		- compute expresions and return 
						  the result of last
 (Subscript[expr, 1]); (Subscript[expr, 2]); (Subscript[expr, 3]);	- compute expresions and do not 
 						  return the results

Expressions sequences

Sin[x]
Sin[{x,2.1,Pi/3}]
Sin[{x,2.1,Pi/3}[[2]]]
(3+4)*5
3+4*5

N[Pi,30]
Pi~N~30
Pi//N

x=4;y=6;x=y+6
x=4;y=6;x=y+6;

a=4+(b=7);
a
b

a=(b=1;c=2)+(d=3);
a
b
c

Be careful! - do not commplicate to much and remember
 Ockham's razor law: 
 "Entia non sunt multiplicanda praeter necessitatem" 
 (entities should not be multiplied beyond necessity)

Algebraic computations

Symbolic

numerical calculations     3 + 62 - 1         ⟶     64
symbolic computations    3x - x + 6 - 4  ⟶     2 + 2x

-1+2x+x^3
x^2+x-4x^2
x y+2 x^2 y+y^2 x^2-2 y x

(x + 2y + 1)(x - 2)^2
Expand[%]
Factor[%]

Sqrt[2]/9801 (4n)! (1103+26390 n)/(n!^4 396^(4n))
Sqrt[1+x]^4
Log[1+Cos[x]]

Basic Mathematica's principle - take an expression and
 apply transformation rules until the expression stops
 changing

Setting values

1+2x/.x->3
1+x+x^2/.x->2-y

x->3+y
x^2-9/.%

rule=x->3+y
x^2-9/.rule

(x+y) (x-y)^2/.{x->3,y->1-a}

x -> value     - define a rule that transforms variable to value
 expr /. rule	- apply a rule to an expr
 x = value		- set a value to a global variable
 x := value		- as above but delayed
 x = .			- clear a value of a variable

Variables can store symbolic values! - so you can assign
 to them anything you want (even a cat if you have one
 around - to be honest it has to be inside;)

Vectors and matrices

{a,b,c}			- vector (({{a}, {b}, {c}}))
 {{a,b},{c,d}}		- matrix (({{a, b}, {c, d}}))

they are represented by lists simply - in fact in Mathematica everything is a list

m={{a,b},{c,d}}    (* define a matrix *)
m[[1]]                                (* take a row *)
m[[1,2]]                          (* take an element *)
m[[All,1]]                     (* take a column *)

v={x,y}
p v+q                       (* combine scalars and vectors *)
v+{xp,yp}+{xpp,ypp}

{x,y}.{xp,yp}
m.v                   (* multiply a matrix by a vector *)
m.m                   (* multiply matrices *)
%//MatrixForm

a . b	 (Dot[a,b])		- a product of vectors, matrices,
						  and tensors

s=Table[i+j,{i,3},{j,3}]   (* generate a matrix *)
s//MatrixForm

Array[a,4]//MatrixForm            (* generate a matrix *)
Array[p,{3,2}]//MatrixForm

DiagonalMatrix[{a, b, c}]        (* generate a matrix *)

({{Table[f,{i,n}], build a length-n vector by evaluating f with i=1,2,…,n}, {Array[a,n], build a length-n vector of the form {a[1],a[2],…}}, {Range[n], create the list {1,2,3,…,n}}, {Range[(Subscript[n, 1]),(Subscript[n, 2])], create the list {(Subscript[n, 1]),(Subscript[n, 1])+1,…,(Subscript[n, 2])}}, {Range[(Subscript[n, 1]),(Subscript[n, 2]),dn], create the list {(Subscript[n, 1]),(Subscript[n, 1])+dn,…,(Subscript[n, 2])}}, {list[[i]]  or  Part[list,i], give the i(^th) element in the vector list}, {Length[list], give the number of elements in list}, {c v, multiply a vector by a scalar}, {a.b, dot product of two vectors}, {Cross[a,b], cross product of two vectors (also input as a×b)}, {Norm[v], Euclidean norm of a vector}})

Functions for vectors

({{Table[f,{i,m},{j,n}], build an m×n matrix by evaluating f with i ranging from 1 to m and j ranging from 1 to n}, {Array[a,{m,n}], build an m×n matrix with i,j(^th) element a[i,j]}, {IdentityMatrix[n], generate an n×n identity matrix}, {DiagonalMatrix[list], generate a square matrix with the elements in list on the main diagonal}, {list[[i]]  or  Part[list,i], give the i(^th) row in the matrix list}, {list[[All,j]]  or  Part[list,All,j], give the j(^th) column in the matrix list}, {list[[i,j]]  or  Part[list,i,j], give the i,j(^th) element in the matrix list}, {Dimensions[list], give the dimensions of a matrix represented by list}})

Functions for matrices

({{Column[list], display the elements of list in a column}, {MatrixForm[list], display list in matrix form}})

Formatting constructs for vectors and matrices

m//MatrixForm
Det[m]
Transpose[m]//MatrixForm
m//Transpose//MatrixForm

Inverse[m]//MatrixForm
%.m//MatrixForm

%//Simplify//MatrixForm

m1={{a,b},{c,d}}//MatrixForm      (* be careful!!! *)
Det[m1]                                                                (* why no result? *)
m1//FullForm

(m2={{a,b},{c,d}})//MatrixForm  (* correct *)
Det[m2]
m2//FullForm

({{c m, multiply a matrix by a scalar}, {a.b, dot product of two matrices}, {Inverse[m], matrix inverse}, {MatrixPower[m,n], n(^th) power of a matrix}, {Det[m], determinant}, {Tr[m], trace}, {Transpose[m], transpose}, {Eigenvalues[m], eigenvalues}, {Eigenvectors[m], eigenvectors}})

Some mathematical operations on matrices.

Algebraic equations

lhs = rhs		- set value
 lhs := rhs		- set delayed value
 lhs == rhs		- equal

2+2==4                (* True *)

x=4;x==6        (* False *)

x=.;x==6          (* Unknown *)

%/.x->4

x^2+2 x-7==0

eqn=%

eqn

Solve[eqn,x]

%//N

result=%;
x/.result
x^2+3x/.result

Mathematica will always solve symbolically any algebraic equation of degree lower than five

Solve[x^4-5 x^2-3==0,x]

Solve[x^5-4 x+2==0,x]

%//N

Solve[Sin[x]==a,x]
Solve[Cos[x]==x,x]
FindRoot[Cos[x]==x,{x,1}]

An example: Straight line and circle intersection

Show[{Graphics[Circle[{0,0},1]],Plot[1-x,{x,-2,2}]}]

Manipulate[Show[{Graphics[Circle[{0,0},1]],Plot[a-x,{x,-2,2}]}],{a,-2,2}]

Solve[x^2+y^2==1&&x+y==a,{x,y},Reals]

Vector/matrix equations

eq=2{{x+2,y+3},{3,1}}=={{3,y},{6,z}};
Solve[eq,{x,y,z}]

eq//MatrixForm     (* does not work - matrices are "inside" *)
MatrixForm/@eq      (* apply function to each element on the first level - Map *)