Pages

Mathematica Basic Functions and Examples

Reading software documentation is boring and Mathematica is a pain so here are some examples of the key functions and their syntax just to get started. I will attempt to update this in the future although I try to find alternatives to Mathematica whenever possible.
# Integration
Integrate[2*Sqrt[2]/(3*a)*x*Sin[2*Pi*x/a]*Sin[3*Pi*x/a], {x, 0, a}]

# Numerical Integration
N[Integrate[4/a^3*r^2*Exp[-2 r/a], {r, 0, a/53600}]]

# Integration over multiple dimensions
Integrate[1/(2*u)*(Q*w*u/(4*Pi*R))^2*((1 - 3*r^2/(5*R^2))^2*Cos[t]^2 + 
(1 - 6*r^2/(5*R^2))^2*Sin[t]^2)*r^2*Sin[t], {t, 0, Pi}, {p, 0, 2 Pi}, {r, 0, R}]

# Finding Intersections
pts = NSolve[x*Cot[x] == -y*Coth[y] && {x, y} \[Element] Circle[{0, 0}, 2*Pi], {x, y}]

# A plot of the above intersections
ContourPlot[{x*Cot[x] + y*Coth[y] == 0 , x^2 + y^2 == 4 Pi^2}, 
{x, -4 Pi, 4 Pi}, {y, -4 Pi, 4 Pi}]

# The Quantum Harmonic Oscillator and some expectation values
Clear[m, \[Omega], \[HBar], n];
(*m=1*)
(*\[Omega]=1*)
(*\[HBar]=1*)

psi[x_, n_] := (m*\[Omega]/(Pi*\[HBar]))^(1/4)*1/Sqrt[2^n*n!]*
  HermiteH[n, Sqrt[m*\[Omega]/(\[HBar])]*x]*
  Exp[-m*\[Omega]*x^2/(2*\[HBar])]
En[n_] = \[HBar]*\[Omega]*(n + 1/2)
En[0]
psi[x_, t_, n_] := (m*\[Omega]/(Pi*\[HBar]))^(1/4)*1/Sqrt[2^n*n!]*
  HermiteH[n, Sqrt[m*\[Omega]/(\[HBar])]*x]*
  Exp[-m*\[Omega]*x^2/(2*\[HBar])]*Exp[-i*En[n]*t/\[HBar]]
psi[x, 0]
psi[x, t, 0]
expX[n_] := Integrate[x*psi[x, n]^2, {x, -Infinity, Infinity}]
expX2[n_] := Integrate[x^2*psi[x, n]^2, {x, -Infinity, Infinity}]
DeltaX[n_] := Sqrt[expX2[n] - expX[n]^2]

# Expand expressions
Expand[Sum[
  1 + e^(I*(Subscript[K, 3] - Subscript[K, 1]) (Subscript[x, i] - 
        Subscript[x, k])) + 
   e^(I*(Subscript[K, 1] - Subscript[K, 2]) (Subscript[x, j] - 
        Subscript[x, i])) + 
   e^(I*(Subscript[K, 2] - Subscript[K, 3]) (Subscript[x, k] - 
        Subscript[x, j])) + 
   e^(I*(Subscript[K, 1]*(Subscript[x, j] - Subscript[x, i]) + 
        Subscript[K, 2]*(Subscript[x, k] - Subscript[x, j]) + 
        Subscript[K, 3]*(Subscript[x, i] - Subscript[x, k]))) + 
   e^(I*(Subscript[K, 1]*(Subscript[x, k] - Subscript[x, i]) + 
        Subscript[K, 2]*(Subscript[x, i] - Subscript[x, j]) + 
        Subscript[K, 3]*(Subscript[x, j] - Subscript[x, k]))), {i, 
   n}, {j, n}, {k, n}]]

# Simplify expressions, '%' uses the result of the previous input
FullSimplify[%]
A couple key differences to note about Mathematica: The use of square brackets instead of parentheses to contain arguments to functions, function names are capitalized, comments are indicated by '(*' and a closing '*)', and user-defined functions are created using ':=' and underscores on any arguments. If possible, I encourage use of open source alternatives such as Octave or Python. However, I have to admit that, when it comes to getting integration and algebra of complicated expressions done quickly, nothing beats Mathematica.