In this talk we will cover some of the built in functions in Mathemtaica that are often ignored by the novice user who is accustomed to procedural programming. Will introduce few of the basic functions for data importing, manipulation and visualization. Will cover in great detail the curve fitting capabilities of Mathematica. We will also go over some not that known features in Mathematica such as speed typing of mathematical formulas, creating your own reusable packages, running Mathematica without the notebook as a command line program, building your own graphical user interfaces and using external controller for data manipulation and visualization.
1. Useful knowledge on Mathematica®
for Physicists
Miroslav Mihaylov
UIC Physics Feb-17-2016
2. The notebook inrerface and the
kernel
◼ The user enters input in the notebook
◼ The input is sent to the Math Kernel via Shift+Enter or Numpad Enter
◼ The kernel performs the computation ans send the result back to the frontend for display
Frontend
Integrate[Exp[-x^2],x]
π
2
Erf[x]
Math Kernel
◼ MathLink the protocol for comunication of the frontend with the Kernel and other
2 PresnetationSlides-Feb-Apr-2016.nb
3. Lists {a1, a2, ..., an}
◼ Generating lists with Table[]
Table expr , i , i min , i max ,
Table expr , i , i min , i max , di , Table expr , i , i 1 , i 2 , …
Tablei, i, 10, 20, 2
{10, 12, 14, 16, 18, 20}
Tablei, 2×i, i, 10, 20, 2
{{10, 20}, {12, 24}, {14, 28}, {16, 32}, {18, 36}, {20, 40}}
Table10i+j, i, 4, j, 3
{{11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43}}
◼ Generating lists with Range[]
Range i max , Range i min , i max , Range i min , i max , di
Range[5]
{1, 2, 3, 4, 5}
Range2, 5, 0.5
{2., 2.5, 3., 3.5, 4., 4.5, 5.}
◼ Table with Random
TableRandom [], 3
{0.929755, 0.0990263, 0.960832}
RandomInteger 10, 4, 3
{{5, 1, 9}, {4, 3, 10}, {6, 9, 3}, {6, 3, 2}}
PresnetationSlides-Feb-Apr-2016.nb 3
4. Lists Representations
◼ Usefull for easy inspection of the elemetns of the list
Table10i+j, i, 4, j, 3 // TableForm
11 12 13
21 22 23
31 32 33
41 42 43
0, -ⅈ, ⅈ, 0 // MatrixForm
0 -ⅈ
ⅈ 0
MatrixForm [{a1, a2}]
a1
a2
4 PresnetationSlides-Feb-Apr-2016.nb
5. Programing in Mathematica
Say we have the list bellow and we would like to reverse the elements of each item in the list
lis= {α, 1}, β, 2, γ, 3;
With procedural programing we would write
tempLis = lis;
Fori = 1, i ≤ Lengthlis, i++,
tempLis i, 1, tempLis i, 2 = lisi, 2, lisi, 1
;
tempLis
{{1, α}, {2, β}, {3, γ}}
Slightly better approach
Table lisi, 2, lisi, 1,
i, 1, Lengthlis
{{1, α}, {2, β}, {3, γ}}
PresnetationSlides-Feb-Apr-2016.nb 5
6. The Mathematica Way
For each element of the list we want to reverse
MapReverse, lis
{{1, α}, {2, β}, {3, γ}}
Same as above written in an alternative syntax
Reverse/@lis
{{1, α}, {2, β}, {3, γ}}
6 PresnetationSlides-Feb-Apr-2016.nb
7. Map[] /@ and Apply[] @@
◼ Map applies a function to each element in a list
Mapf, a, b, c
{f[a], f[b], f[c]}
◼ Apply changes the structure of the expression
Applyf, a, b, c
f[a, b, c]
ApplyPlus, a, b, c, d
a+b+c+d
ApplyPlus, a, b, c, {α, β, γ}
{a+α, b+β, c+γ}
PresnetationSlides-Feb-Apr-2016.nb 7
10. There is a Function for that,...
◼ If you wanted to bo something in Matheatica
chances are that there exists a built in function called
DoSomething[]
Solve expr , vars , FindRoot lhs == rhs , x , x0 , FindPeaks data , σ ,
EstimatedBackground data , σ , Gather list , test , Select list , crit ,
GroupBy elem 1 , elem 2 , … , spec , red , Split list , test ,
ImageConvolve image , ker , ListConvolve ker , list , k , ImageData image , type ,
Convolve f , g , x , y , FourierTransform expr , t , ω , Fold f , x , list ,
NDSolve eqns , u , x , xmin , xmax , NIntegrate f , x , xmin , xmax ,
Evaluate expr , FourierSeries expr , t1 , t2 , … , n1 , n2 , … , ListPlot y1 , y2 , … ,
ListLinePlot y1 , y2 , … , ListLogPlot y1 , y2 , … , Plot f , x , xmin , xmax ,
TimeSeriesModelFit data , mspec , NonlinearModelFit data , form , cons , β1 , … , x1 , …
◼ Your core logic should not take more than a
single line.
10 PresnetationSlides-Feb-Apr-2016.nb
11. Math Input Shortcuts
Switching between input form and Standard Form for selected cell in the notebook menu select
Cell-> Convert to-> StandardForm or the shortcut Shift+Ctr+N
Input form Standard Form Keyboard Shortcut
x^2 xn
x Ctr-[6] n
Subscript[x, j] xj x Ctr+_ j
Sqrt[x] x x Ctr+[2] x
x/n x
n
x Ctr+/ x
PresnetationSlides-Feb-Apr-2016.nb 11
12. Shortcuts Continued
Navigating throight different placeholders of the exoressins with the Tab
To exit the Ctrl + Space
Input form Standard Form Keyboard Shortcut
Integrate[, {, , }] ∫
ⅆ Esc-dintt-Esc
Sum[x, {, , }] ∑=
Esc-sumt-Esc
Product[, {, , }] ∏=
Esc-prodt-Esc
You can access the input palettes from the notebook menu Palletes->Basic Math Assistant
12 PresnetationSlides-Feb-Apr-2016.nb
13. Special Characters Shortcuts
Standard
Form
Keyboard
Shortcut
Notes
π Esc-pp-Esc The Pi 3.1415..
ⅇ Esc-ee-Esc The natural exp
ⅈ Esc-ii-Esc The imaginaryunit
∞ Esc-inf-Esc Infinitysymbol
ϵ Esc-e-Esc Greek epsilon
η Esc-et-Esc Greek etha
Similarly for the upper case greek letters Esc-G-Esc wouth output Γ Δ Ω
PresnetationSlides-Feb-Apr-2016.nb 13
18. Determining the goodness of fit
nlm "ANOVATable"
DF SS MS
Model 4 3513.73 878.433
Error 7 5.11795 0.731136
Uncorrected Total 11 3518.85
Corrected Total 10 2912.13
nlm "FitResiduals"^2 // Total
5.11795
ListPlotnlm "FitResiduals", Filling→ Axis
2 4 6 8 10
-0.5
0.5
1.0
1.5
5.91404
18 PresnetationSlides-Feb-Apr-2016.nb
19. Fitting a subset of parameters
◼ Somtimes we might need to impose restrinctions on
some of the parameters in our model
F[Vcm , Vo, ϕ, T] /. Vo → 23.05, ϕ → 0.81
Vcm +23.05Sin0.81+
2πt
T
◼ Fitting only the subset of parameters while keeping
the other ones fixed
nlm = NonlinearModelFitdataV,
F[Vcm , Vo, ϕ, T] /. Vo → 23.05, ϕ → 0.81, Vcm , T, 10, t;
nlm "BestFitParameters "
{Vcm → 6.68274, T → 10.4396}
◼ Getting our final model
Normal nlm /. Vo → 23.05, ϕ → 0.81
6.68274+23.05Sin[0.81+0.601862t]
PresnetationSlides-Feb-Apr-2016.nb 19
22. Manipulate with different
ControlType
ManipulateSolute,
Solute, "H2O", "DCE", "Hexane", "Toluene", "Dodecane", ControlType -> PopupMenu
Solute Toluene
Toluene
Manipulatey, y, 0, 1, ControlType → Slider2D
y
0
◼ Some of the many possible values for ControlType
Animator u , umin , umax , Checkbox x ,
InputField x , RadioButtonBar x , val1 , val2 , …
22 PresnetationSlides-Feb-Apr-2016.nb
23. Working with dynamically updated
content
◼ Dynamic[expr ]
Controlx, 0, 0, {1, 1}
Dynamic [x]
{0., 0.}
Dynamic GraphicsLocatorDynamic [x], PlotRange → 1, Dynamic [x]
, {0., 0.}
◼ DynamicModule[{x = x0 , y = y0 , … }, expr ]
Maintains a local instance of x,y,.. and preserves their values across notebook sessions
PresnetationSlides-Feb-Apr-2016.nb 23
28. A complete example
Fit
C 10
A 15
ϕ 0.5
T 4
0 T->4 T chk->False
Model usemodel
Fit Res res
0 2 4 6 8 10
-10
0
10
20
30
28 PresnetationSlides-Feb-Apr-2016.nb
29. All work no play makes Jack a dull
boy
◼ Game Controller integration
ControllerInformation []
Controller Device 1: Logitech Logitech Dual Action
Raw Product Name "Logitech Logitech Dual Action "
Device Type Linux Joystick Device
Raw Controller Type Joystick
Mathematica Controls 36 controls
X $Failed
Y $Failed
Z $Failed
X1 $Failed
Y1 $Failed
Z1 $Failed
X2 $Failed
Y2 $Failed
X3 $Failed
Y3 $Failed
X4 $Failed
Y4 $Failed
X5 $Failed
Y5 $Failed
X6 $Failed
B1 $Failed
B2 $Failed
B3 $Failed
B4 $Failed
B5 $Failed
B6 $Failed
B7 $Failed
B8 $Failed
B9 $Failed
B10 $Failed
B11 $Failed
B12 $Failed
BLB $Failed
BRB $Failed
JB $Failed
JB1 $Failed
JB2 $Failed
Select Button $Failed
Start Button $Failed
TLB $Failed
TRB $Failed
Show Dynamic Values
Raw Controls 18
PresnetationSlides-Feb-Apr-2016.nb 29
31. Computing without the frontend
◼ Create an ASCII file scriptname.m
#!/usr/local/bin/MathematicaScript -script
<<myPackageWmyFunctions`;
a=22;b=34;
For[i=0, i<30, i++,
For[j=0, j<30, j++,
For[k=0, k<30, k++,
(*Do the work here and print some results*)
parA=j*a;parB=k*c
SomeResult=MyFunc[parA,parB]
Print[l,” “, i,” “, j,” “, k,SomeResult];
]
]
]
◼ From the command line run
$math -run <scriptname.m
PresnetationSlides-Feb-Apr-2016.nb 31
32. Calling Exteranl programs
◼ Opening system program
Run"notepad"
Run"calc"
◼ Executing command line script and outputing the
result to a file
Run"awk -f AWK4math /myawkscript .awk "<>filename
" > tmplocal /fileprefix_"<>fillevar<>".dat"
◼ Open the specified targeth path with the default
program
SystemOpen "phys.uic.edu"
SystemOpen "filename .docx"
32 PresnetationSlides-Feb-Apr-2016.nb
33. Interacting with MySQL database
◼ Connect to the database
Needs"DatabaseLink`";
JDBCDrivers"MySQL(Connector/J)";
conn = OpenSQLConnectionJDBC"MySQL(Connector/J)", "localhost/test_db",
"Username " → "root", "Password" → ""
◼ Select from the database
SQLSelectconn, "table_name ", "MaxRows" → 4, "ShowColumnHeadings " → True // TableForm
◼ Inserting
SQLInsertconn, "table_name ", "col_a", "col_b", 3, 10.5
PresnetationSlides-Feb-Apr-2016.nb 33
34. And many more applictions
THANK YOU
34 PresnetationSlides-Feb-Apr-2016.nb