# Mathematica

I strongly suggest you to visit official webpage for the details of the syntax at here. Instead of asking what the commands do, try out the commands what they do. There are nearly 6000 built-in commands. I will only list the commands which people (or I) use most frequently.

## Basics

• To execute commands in a cell, hit “Shift+Enter”
• Functions uses square brackets instead of round brackets
• Case sensitive
• End the expression by a semicolon ;. Also, semicolon suppress the output
• Put ? in front of any commands you don’t know. For example: ?For
• Comment is (* This is a comment *)
• Make a habit of putting spaces between variables, operators (+, -, *, …), functions and so on. This makes your codes easier to read.

### Binary operation

• x2 does not means x times 2. Instead it will be considered as a new variable.
x^y            (* x to the y-th power *)
x^y            (* x to the y-th power *)
x*y            (* x times y *)
x y            (* x times y (one or more spaces separate the variables) *)
2 x            (* 2 times x *)


### Variable assignments

x = value             (* Assign a value to the variable x *)
x = y = value         (* Assign a value to both the variable x and y *)
x := value            (* Assign the value to x, but don't do it right away; wait until x is actually used *)
x == y                (* Test whether x is equal to y *)
x === y               (* Test whether x is identical to y. SameQ[x, y] *)


### Mathematical constants

E                           (* Base of the natural Log, about 2.71928 *)
Pi                          (* About 3.14159. pi will be treated as variable *)
I                           (* Square root of -1. i will be treated as variable *)
Infinity                    (* Mathematical infinity *)
Infinity+Infinity           (* Indeterminate form $\inf+\inf$ *)
Infinity/Infinity           (* Indeterminate form $\inf/\inf$ *)
ComplexInfinity             (* Infinity in complex plane *)


### Replacements

expr /. x->new_value             (* Replace x value to new value on this expression expr *)
expr /. {x->val,y->yval}         (* Perform replacement simultaneously *)


### Containers

{a,b,c, ...}                             (* A list of three objects or more *)
{}                                       (* An empty list *)
d[[n]]                                   (* nth item in the list d. Note the double brackets *)
Map[f, {1, 2, 4, 6, 5, 8}]               (* Returns {f[1], f[2], f[4], f[6], f[5], f[8]} *)
mat={{1, 2}, {4, 5}, {7, 8}}             (* Creates matrix of size 3x2 *)
mat[[1,2]]                               (* Pick an element of 1st row and 2nd column *)


### Iterators

• Iterator means a statement which says to repeat something. For example: $\sum_{n = 2}^{20} d(n)$ where the iterator is n which ranges from 2 to 20.
Sum[d[[n]], {n, 2, 20}]                  (* Sum as d[[2]] + d[[3]] + ... + d[[20]], n is an iterator *)
Plot[f[x], {x, a, b}]                    (* Plot the graph of the expression f[x] from x = a to x = b inclusive. x is an iterator *)


• Don’t forget to put underscore while defining a function variable on the left side. This treat variable as a placeholder.
f[x_] := 2x + 1                (* Defines a new function $f(x) = 2x + 1$ *)
Function[x, x^3]               (* Using built-in function to create function *)
Function[x, x^3][10]           (* Takes x value to be 10 *)
f[x__] := Length[{x}]          (* Double underscore is called BlankSequence. Takes more inputs at once. For example: {f[x, y, z], f[]} returns {3, f[]} *)


### Shorthand notations

%                                       (* Output just generated *)
%%                                      (* Output just one before *)
%%%                                     (* Output just two before *)
%n                                      (* Returns output line number Out[n] *)
Length@{1,2,3}                          (* You don't have to move to the end of the expression to match the square bracket *)
{1, 2, 4, 6, 5, 8} // Length            (* Postfix notation. Works same as one line above *)
(#^3) &[3]                              (* Equivalent to Function[x, x^3][3]. # serves a placeholder for variable, while the & symbol precedes the value you wish to substitute into the function *)
f /@ {1, 2, 4, 6, 5, 8}                 (* Same as Map[f, {1, 2, 4, 6, 5, 8}] *)
mat // MatrixForm                       (* Turn a matrix array into matrix form *)


### Looping Constructs and Conditional

• You can exclude the iterator part {i, n} and use only n (means evaluate expression $n$ times).
Table[expr,{i,n}]                      (* Build up a table by looping over variables *)
Do[expr,{i,n}]                         (* Evaluate an expression looping over a variable. For example: Do[Print[n^2], {n, 4}] *)
Do[expr, {i, imin, imax, di}]          (* Uses steps. For example: Do[Print[n], {n, -3, 5, 2}] means n goes from -3 to 5 in steps of 2 *)
While[condition,expr]                  (* Evaluate an expression while a condition is true. For example: n = 1; While[n < 4, Print[n]; n++] *)
For[start,test,incr,body]              (* Executes start, then repeatedly evaluates body and incr until test fails to give True. For example: For[i=0,i<4,i++,i=2*i;Print[i]] *)
If[condition, t, f]                    (* Gives t if condition evaluates to True, and f if it evaluates to False. For example: abs[x_] := If[x < 0, -x, x] *)


## Built-in functions

### Useful functions

ClearAll["Global*"]                  (* Clear all the value assigned *)
Clear[x]                              (* Clear the value previously assigned to x (if any) *)
SetDirectory["<dirname>"]             (* Set directory to look up for file or write. <dirname> means full path of the directory *)
Import["file.txt", "Table"];          (* Import the data from file.txt and make a table out of it *)


### Common mathematical functions

• Start the function name with capital letter
• In inverse trigonometric function, remember to capitalize not only the first letter A but also the first letter of trigonometric function. For example: ArcSin[x]
N[Pi, 30]                    (* Return mathematical constant Pi with 30 decimals *)
Sqrt[x]                      (* Square root of x *)
Exp[x]                       (* Base of the natural log *)
Log[x]                       (* Natural logarithm of x *)
Log[b,x]                     (* Logarithm of x to the base b *)
Sin[x], Cos[x], Tan[x],      (* Trigonometric functions *)
Csc[x], Sec[x], Cot[x]
ArcSin[x], ArcCos[x],        (* Inverse Trigonometric functions *)
ArcTan[x], ArcCsc[x],
ArcSec[x], ArcCot[x]
n! or Factorial[n]           (* Factorial of n. Factorial[n] also works *)
Abs[x]                       (* Absolute value of x (even if x is complex) *)
Round[x]                     (* Closest integer to x *)
Floor[x]                     (* Largest integer <= x. Floor[2.1] = 2, but Floor[-2.1] = -3 *)
Ceil[x]                      (* Smallest integer >= x. *)
Mod[n,m]                     (* Remainder on division of n by m (for integers only) *)
PolynomialRemainder[p,q,x]   (* If p and q are polynomials in x *)
Random[]                     (* Random number between 0 and 1 *)
Max[x,y, ...]                (* Largest of x, y, ... (input are numbers) *)
Min[x, y, ...]               (* Smallest of x, y, ... *)


### Algebraic manipulation

Solve[x^2 - 2x + 1 == 0, x]              (* Solves the equation $x^2 - 2x + 1 = 0$ *)
Roots[f[x] == 0, x]                      (* Finds the roots of a polynomial equation. Only exact solutions will be reported *)
NRoots[f[x]==0,x]                        (* Finds the roots of a polynomial equation but numerically, i.e. approximately *)
FindRoot[f[x]==0,{x,a}]                  (* Find roots of f[x] = 0 numerically, starting at x = a. Works for non-polynomials, but may fail to find the roots, or all of the roots, even when they exist *)
Expand[expr]                             (* Multiples out products and powers *)
ExpandAll[expr]                          (* Apply "Expand" everywhere throughout in expr *)
Factor[poly]                             (* Factors a polynomial over the integers *)
FactorTerms[poly]                        (* Pull out common factors that appear in each term of a polynomial *)
Together[expr]                           (* Put all terms over a common denominator *)
Apart[expr]                              (* Separate into terms with simpler denominators *)
Cancel[expr]                             (* Cancel common terms between numerators and denominators *)
Collect[expr,x]                          (* Group together powers of x *)
Simplify[expr]                           (* Turns the expression into simplest form possible *)
Numerator[expr]                          (* Returns the numerator of expression *)
Denominator[expr]                        (* The denominator of expr *)


### Derivatives and Integrals

• If mathematica cannot integrate, it will return the expression unchanged.
D[y,x]                       (* Derivative of the expression y with respect to x *)
f'[x]                        (* Derivative of f[x] with respect to x (if f has previously been defined as a function) *)
D[y,x,x], f''[x]             (* Second derivative with respect to x *)
Integrate[f[x],x]            (* Indefinite integral of f[x] with respect to x *)
Integrate[f[x],{x,a,b}]      (* Definite integral of f[x] with respect to x on the interval (a,b) *)
Limit[f[x],x->a]             (* Limit of f[x] as x approaches to a *)


## Tips and Tricks

### Pair two arrays

x = {1, 2 , 4, 5}
y = {1, 4, 16, 25}
xy = Transpose[{x, y}]    (* Or you can also do: [email protected]{x, y} *)


### $\LaTeX$ typesetting

• You need to install pdflatex and ghostscript to act as a backend program to use MaTeX package. Assuming you have meet the requirement. For more see at references.
TeXstyle = {FontFamily -> "Times", FontSize -> 12};

Plot[Sin[phi], {phi, 1, 2}, Frame -> True, BaseStyle -> TeXstyle,
FrameLabel -> {\[Phi], ToExpression["\\sin(\\phi)", TeXForm, HoldForm]}]

Get["MaTeX"]
MaTeX["\\sin(\\phi)"]

• Don’t try to use \MaTeX["\\sin(\\phi)"] in the second parameter of FrameLabel because it rasterize the label. You don’t need MaTeX to do it. If you don’t believe me, you can proceed and full zoom-in the export pdf graphics :)

### Time consumed by some cells

timestampstart = DateObject[];
Print["Simulation Started at: ", timestampstart]
(* Cells here *)
Print["Time taken to finish simulation: ", DateObject[] - timestampstart]


## Hacks

### Hide and show cell

• Function for closing all cells inputs:
CloseAllInputsCells[] := Module[{nb, cells},
nb = EvaluationNotebook[];
cells = Cells[nb, CellStyle -> "Input"];
SetOptions[#, CellOpen -> False] & /@ cells;
];

• Function for recovering or made visible again:
 OpenAllInputsCells[] := Module[{nb, cells},
nb = EvaluationNotebook[];
cells = Cells[nb, CellStyle -> "Input"];
SetOptions[#, CellOpen -> True] & /@ cells;
];

• How to use it?
1. Copy / Paste both functions above in a fresh / new notebook and run the notebook.
2. Inside your target Notebook, at the end of your document, run CloseAllInputsCells[] . All input cells will be closed.
3. For recovering all inputs again, run OpenAllInputsCells[]

Note: You can also do by double-clicking any output cell bracket.