Scientific & Engineering Programming

Lecture II

Mathematica basics 2

Robert Muszyński

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

Copyright 2018 RM

How to enter expressions

Use keyboard

just type what the keyboard allows to

use escape sequences (Esc alpha Esc  gives α (can be abbreviated: Esc a Esc), Esc int Esc  gives ∫  - see “Letters  and Letter-like Forms”  help and “Keyboards Shortcuts Listing” )

∫(α^2)\[DifferentialD]α       (* typed with Esc intt Esc, Esc a Esc, Ctrl+^ *)

Use mouse and palettes

useful pallets: Basic Math Assistant, Writing Assistant, Classroom Assistant

just click

Use help and examples

Copy and Paste technique ;)  (ask the question, follow the >> sign, and take what you need)

?NDSolve

Use natural language

set Free-form input from cell menu (equal sign at the cell beginning)

Observe: Everything you enter is organized in cells, which can be grouped  automatically

you can split and merge cells as required - see “Cell Groups  and Outlining”  help

you can change the cells layout - see “Stylesheets”, “Notebook Formatting and Styling”, “Notebook and Interface Customization”  helps

Functions

Defining functions

f[x_]:= x^2
f[3]
f[a+2]

?f

({{f[x_]:=x^2, define the function f}, {?f, show the definition of f}, {Clear[f], clear all definitions for f}})

By default user defined functions are not listable

g[x_]:=something[x];
g[{3,x^2+4x-7,(Subscript[zm, 1])+4(Subscript[zm, 1])}]
SetAttributes[g,Listable];
g[{3,x^2+4x-7,(Subscript[zm, 1])+4(Subscript[zm, 1])}]

f[{3,x^2+4x-7,(Subscript[zm, 1])+4(Subscript[zm, 1])}] (* but can look like listable! *)

Functions with several arguments

expr[x_,xmax_]:=(x+xmax)^2/(x-xmax)^2
expr[g,12]
expr[x^2+3,y-7]

expr[{a,b,c},{1,2,3}]
expr[{a,b,c},{1,2,3,4}]

Immediate versus delayed

a=7;
gi[x_]=x^2+a;
gd[x_]:=x^2+a

?gi

?gd

a=11;
gi[z]
gd[z]

Functions as procedures

slv[lhs_,var_]:=Solve[lhs==0,var]
slv[x^2+4x-4,x]

exprod[n_]:=Expand[Product[x+i,{i,1,n}]]
exprod[5]

cex[n_,i_]:=(t=exprod[n];Coefficient[t,x^i]) 
cex[5,3]            (* defines/uses a global variable t! *)
t

({{((Subscript[expr, 1]);(Subscript[expr, 2]);…;(Subscript[expr, n])) , a sequence of expressions to evaluate}, {Module[{a,b,…},proc], 	a procedure with local variables a, b, … }})

Functions with local variables

lcex[n_,i_]:=Module[{u},u=exprod[n];Coefficient[u,x^i]]
lcex[5,3]
u

Conditionals

If[7>8,Print[x],Print[y]]

f[x_]:=If[x>0,1,-1]     (* step function *)

f/@Table[i,{i,-3,3}]     (* why not f[Table[...]]? *)

g[x_]:=1/;x>0             (* alternative: the positive part *)
g[x_]:=-1/;x<=0        (* the negative part *)
					   (* one of the conditions can (should) be ommited *)

g/@Table[i,{i,-3,3}]

Plot[g[x],{x,-5,5}]

Three-valued condition

If[z>8,Print[true],Print[false]]
If[z>8,Print[true],Print[false],Print[unknown]]

lhs := rhs /;test
 If[test,then,else,unevaluated]

({{Which[(Subscript[test, 1]),(Subscript[value, 1]),(Subscript[test, 2]),…], evaluate the (Subscript[test, i]) in turn, giving
the value associated with the first
one that is True}, {Switch[expr,(Subscript[form, 1]),(Subscript[value, 1]),(Subscript[form, 2]),…], compare expr with each of the (Subscript[form, i]),
giving the value associated with the 
first form it matches}, {Switch[expr,(Subscript[form, 1]),(Subscript[value, 1]),(Subscript[form, 2]),
                                                    …,_,def], use def as a default value}, {Piecewise[{{(Subscript[value, 1]),(Subscript[test, 1])},…},def], give the value corresponding to
 the first (Subscript[test, i]) which yields True}})

h[x_]:=Which[x<0,x^2,x>5,x^3,True,0]
h[-5]
h[2]

r[x_]:=Switch[Mod[x,3],0,a,1,b,2,c]
r[7]

Loops and looping

For[i=0,i<4,i++,Print[i^2]]

A comma delimits the parts of  For; a semicolon delimits the parts of procedures:

For[i=1;l=x,i^2<10,i++,l=l^2+i;Print[l]]

Do[Print[i^2],{i,4}]

Do[Print[i],{i,-3,4,2}]

Do[expr,{(Subscript[i, max])}]			Do[expr,{i,(Subscript[i, min]),(Subscript[i, max]),di}]
 Do[expr,{i,(Subscript[i, max])}]			Do[expr,{i,{(Subscript[i, 1]),(Subscript[i, 2]),…}}]
 Do[expr,{i,(Subscript[i, min]),(Subscript[i, max])}]		Do[expr,{i,(Subscript[i, min]),(Subscript[i, max])},{j,(Subscript[j, min]),(Subscript[j, max])},…]
 For[start,test,incr,body]

Watch out for commas and semicolons!

({{While[test,body], evaluate body repetitively, so long as
test is True}, {Catch[expr], evaluate expr until Throw[value] is encountered,
then return value}, {Nest[f,expr,n], apply f to expr n times}, {FixedPoint[f,expr], start with expr, and apply f repeatedly until
the result no longer changes}, {NestWhile[f,expr,test], start with expr, and apply f repeatedly until
applying test to the result no longer 
yields True}, {Table[f,{…}], give a list of the values of f …}})

Catch[Do[Print[i];If[i>3,Throw[i]],{i,10}]]

Map (/@)	— map a function over a list
Apply (@@) 	— apply a function to a list
MapIndexed 	— map a function, including index information
MapAt 		— map a function at particular positions
Scan 		— scan over every element of a list, applying
              a function
FoldList 	— successively apply a function, "folding in"
              elements
MapThread 	— map a function across corresponding elements

Timing issues

Timing[Do[,{10^6}]]
Timing[Do[,{1000000}]]

Timing[i=1;While[i<10^6,i++]]
Timing[i=1;While[i<1000000,i++]]

Timing[For[i=1,i<10^6,i++]]
Timing[For[i=1,i<1000000,i++]]

Timing[Table[0,{10^6}]][[1]]
Timing[Table[0,{10^6}]]

Graphics

Basic 2D plotting

Plot[Sin[x],{x,0,6Pi}]
Plot[{Sin[x],Sin[2x],Sin[3x]},{x,0,2Pi},PlotLegends->"Expressions"]

fig1=Plot[2Sin[x]+x,{x,0,15},Filling->Bottom]
fig2=Plot[{Sin[x]+x/2,Sin[x]+x}, {x, 0, 15},Filling->{1->{2}}]
Plot[Evaluate[Table[BesselJ[n,x],{n,4}]],{x,0,10},Filling->Axis]

Show[fig1,fig2,AxesLabel->{x,y}]

??Plot

Plot[Tan[x],{x,-3,3}]
Plot[Tan[x],{x,-3,3},Exclusions->{-Pi/2,Pi/2}]

LogPlot[E^x^2,{x,1,5}]
LogLogPlot[E^x^2,{x,1,5}]

ParametricPlot[{2Sin[t],Cos[t]},{t,0,2Pi}]
PolarPlot[Cos[t]^2,{t,0,2Pi}]
ContourPlot[x^3+x y^2+y==0,{x,-1,1},{y,-10,10}]

Plot[]				ParametricPlot[]
 LogPlot[]			PolarPlot[]
 LogLogPlot[]		ContourPlot[]
 LogLinearPlot[]

Basic 3D plotting

Plot3D[Sin[x y],{x,-Pi,Pi},{y,-Pi,Pi}]
Plot3D[{Sin[x y],Sin[2x]Sin[3y]},{x,-Pi,Pi},{y,-Pi,Pi}]

??Plot3D

Plot3D[Tan[x^2 +y^2],{x,-2,2},{y,-2,2}]
Plot3D[Tan[x^2 +y^2],{x,-2,2},{y,-2,2},PlotRange->100]
Plot3D[Tan[x^2 +y^2],{x,-2,2},{y,-2,2},PlotRange->100,PlotPoints->8,MaxRecursion->8]

?*3D*

ParametricPlot3D[{r Cos[t],r Sin[t],Log[r^(1/2)]},{r,0.1,1},{t,0,2Pi}]
ParametricPlot3D[{5 Cos[u],5 Sin[u],u+Sin[u]},{u,-2Pi,2Pi}]

fig3=SphericalPlot3D[1,{t,0,Pi},{p,0,2Pi},PlotStyle->Opacity[0.6]]
fig4=ContourPlot3D[x^2+y^2-z^2==0,{x,-2,2},{y,-2,2},{z,-2,2}]
RevolutionPlot3D[{{2+Cos[t],Pi+1/2Sin[t]},{Sin[t],t}},{t,0,2Pi},{θ,0,2Pi}]

Show[fig3,fig4]

Plot3D[]				SphericalPlot3D[]	
 ParametricPlot3D[]		RevolutionPlot3D[]
 ContourPlot3D[]

Data plotting

sdata=Table[1. Sin[2 i],{i,0,2 Pi,Pi/12}]
ListPlot[sdata]
ListLinePlot[sdata]

ListPlot[Prime[Range[25]],Filling->Axis]

Manipulate[ListPolarPlot[Table[Cos[i /n]^m,{i,-k Pi,t Pi,Pi/d}],PlotStyle->{PointSize[s],Red},ImageSize->{400,400},Axes->None,PlotRange->{{-1.1,1.1},{-1.1,1.1}}],{{n,0.32},0.1,5,0.01},{m,1,4,1},{{t,4.14},2,6},{{d,100},10,200,10},{{k,4},-1.5,8},{{s,0.006},0.003,0.01,0.001}]

data=Table[Sin[j^2+i^2],{i,0,Pi,Pi/30},{j,0,Pi,Pi/30}];
ListPlot[{data[[1]],data[[19]]}]
ListPointPlot3D[data]
ListPlot3D[data]

ListPlot[]				ListPlot3D[]	
 ListPolarPlot[]		ListPointPlot3d[]

Other plotting

ContourPlot[Cos[x]+Cos[y]==1/2,{x,0,4Pi},{y,0,4Pi}]
ContourPlot[Cos[x]+Cos[y],{x,0,4Pi},{y,0,4Pi}]

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

ContourPlot3D[ Cos[x]Sin[y]+Cos[y]Sin[z]+Cos[z]Sin[x]==0,{x,-2π,2π}, {y,-2π,2π},{z,-2π,2π},ContourStyle->Directive[FaceForm[Orange,Red],Specularity[White,30]],Mesh->None]

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

VectorPlot[Evaluate[D[Sin[x y],{{x,y}}]],{x,0,1},{y,0,1}]

StreamPlot[{-x^2+y-1,x-y^2+1},{x,-3,3},{y,-3,3}]

VectorPlot3D[{x,y,z},{x,-1,1},{y,-1,1},{z,-1,1}]

scalarField=x^2-y^2-z
vectorField=D[scalarField,{{x,y,z}}]
VectorPlot3D[vectorField,{x,-2,2},{y,-2,2},{z,-2,2}]

v=VectorPlot3D[vectorField,{x,-2,2},{y,-2,2},{z,-2,2},VectorPoints->25,VectorScale->{0.1,Scaled[0.5]},RegionFunction->Function[{x,y,z},-0.1≤scalarField<=0.1]]

BarChart[{{1,2,3},{1,3,2},{5,2}},ChartLegends->{"a","b","c"}]
BarChart[Range[6],ChartElementFunction->"GlassRectangle",ChartStyle->"Pastel"]
BarChart3D[Range[6],ChartElementFunction->"ProfileCube",ChartStyle->"Pastel"]

g=ExampleData[{"Geometry3D","Cow"}];
BarChart3D[Range[5],ChartElements->g,ChartStyle->"Pastel"]

PieChart[{1,2,3,4}]
PieChart[Range[7],SectorOrigin->{Automatic,1},ChartStyle->54,ChartBaseStyle->EdgeForm[],ChartElementFunction->"GlassSector"]
PieChart[Table[Style[1,Hue[h,s,1]],{s,0,1,.1},{h,0,1,.1}]]

PieChart3D[{1,2,3,4}]
PieChart3D[{1,2,3,4},SectorOrigin->{Automatic,1}]
PieChart3D[{Range[6],Range[10]},ChartStyle->61,ChartBaseStyle->Directive[Opacity[0.8],Specularity[White,30],EdgeForm[Gray]]]

data={{51852,"B"},{88168,"C"},{73897,"D"},{93933,"E"},{19289,"F"},{79623,"G"},{48262,"H"},{29162,"I"},{96878,"J"},{81241,"K"},{40652,"L"},{37581,"M"},{2882,"N"},{45608,"R"},{72570,"S"},{44799,"T"},{71887,"U"},{78170,"V"}};
labeler=(Placed[
Row[{#2,#1},","]& @@@ data,"RadialCallout",Style[#,FontFamily->"Helvetica",FontSize->10]&]);
PieChart3D[data[[All,1]],ChartStyle->54,SectorOrigin->{{110Degree,1},1},ChartElementFunction->"ProfileSector3D",ChartLabels->labeler,ChartBaseStyle->EdgeForm[],Background->GrayLevel[0.9]]

?*Plot*

?*Chart*