# Mathematica

I strongly suggest you visit the official webpage for the details of the syntax 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 use 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 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 *)
mul = {16, 2, 3, 4, 12, 1, 5, 0, 13, 14, 90}; (* Defining an array to understand span (in other language, it's called array slicing or simply slicing)*)
mul[[1;;3]] (* The first three items in the array. ;; means Span in Mathematica language *)
mul[[;; ;; 2]] (* Every other item in the array, [Out]= {16, 3, 12, 5, 13, 90} *)
mul[[2 ;; ;; 3]] (* Every third item from the second item, [Out]= {2, 12, 0, 90} *)
mul[[;;]] (* All items in the array *)
mul[[2;;]] (* All items in the array except the first two *)
mul[[-4;;]] (* Last four elements of the array *)
mul[[-4;;-2]] (* Last three elements of the array *)
mul[[-4;;-2, 1]] (* Last three elements of the array, and the first element *)
mul[[-4;;-2, 1;;-1]] (* Last three elements of the array, and the first element, and the last element *)
Tally[mul] (* Count the number of each element in the array *)
Map[f, {1, 2, 4, 6, 5, 8}] (* [Out]= {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 *)
mat[[All, 1]] (* Pick all the elements of first column *)
mat[[1 ;; 2, 1]] (* Pick first two element of column 1. For more description, see references below. *)
mat[[;;, 1]] (* Pick all elements of column 1 *)
mat[[;;, 1 ;; 2]] (* Pick all elements of first two columns *)
mat[[;;, 1 ;; 2, 1]] (* Pick all elements of first two columns, and the first element of the third column *)
Tally[mat] (* Count the number of each element in the matrix *)
arr={0.1, 0.12, 1, 2, 3} (* Define a list, we will use it in example below *)
{RankedMin[arr, 1], RankedMin[arr, 2]} (* Get first two minimum from the `arr` list *)
RankedMax[arr, -1] (* Get first largest element in the `arr` list *)
```

### 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 *)
```

### Define your own function

- 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[]} *)
fun[x_, n_: 2] := x^n (* Defines a new function with default parameter value *)
fun[3] (* Gives 9 *)
fun[3, 5] (* Gives 243 *)
```

### 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

### $\LaTeX$ typesetting

- Mathematica is very good at creating amazing plots but, unfortunately it’s really bad at $\LaTeX$ typesetting. By the way, there is a way to do it.

#### Easy solution

- Install the “Latin Math Font” in your computer.

```
(* Define a function *)
displayLaTeX[string_] := DisplayForm[ToBoxes@TraditionalForm@ToExpression[string, TeXForm, HoldForm]]
(* Define a style *)
style = {FontFamily -> "Latin Modern Math", FontSize -> 12};
(* Minimal example *)
plot = Plot[Sin[phi], {phi, 1, 2}, LabelStyle -> style, Frame -> True, FrameLabel -> {displayLaTeX["\\phi"], displayLaTeX["\\sin(\\phi)"]}]
(* Example with legends *)
plot = Plot[Sin[phi], {phi, 1, 2}, LabelStyle -> style, Frame -> True, FrameLabel -> {displayLaTeX["\\phi"], displayLaTeX["\\sin(\\phi)"]} , PlotLegends -> Placed[{displayLaTeX["\\sin(\\phi)"]}, {0.8, 0.3}]]
(* More tricky example: when you want to label \sin(\phi)^{(1 + \phi)} then, the mathematica will suppress the parenthesis i.e. \sin(\phi)^{1 + \phi}*)
(* We need to use Superscript and Row buit-in functions wisely. *)
plot = Plot[Sin[phi]^(1 + phi), {phi, 1, 2}, LabelStyle -> style, Frame -> True, FrameLabel -> {displayLaTeX["\\phi"], Superscript[displayLaTeX["\\sin(\\phi)"], Row[{"(", displayLaTeX["1+\\phi"], ")"}]]}, PlotLegends -> Placed[{Superscript[displayLaTeX["\\sin(\\phi)"], Row[{"(", displayLaTeX["1+\\phi"], ")"}]]}, {0.8, 0.3}]]
(* Export the plot into pdf format *)
Export["plot.pdf", plot];
```

#### Alternative solutions

**Using MaTeX**

- 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.

```
(* Import the package *)
Get["MaTeX`"]
(* Usage *)
MaTeX["\\sin(\\phi)"]
(* Example plot *)
Plot[Sin[phi], {phi, 1, 2}, Frame -> True, FrameLabel -> {MaTeX["\\phi"], MaTeX["\\sin(\\phi)"]}]
```

- Beaware that
`\MaTeX["\\sin(\\phi)"]`

in the`FrameLabel`

rasterizes the label which I don’t like. I wish it doesnot rasterize.

**Using psfrag**

- psfrag is a $\LaTeX$ package that allows one to overlay Encapsulated PostScript (EPS) figures with arbitrary $\LaTeX$ constructions, properly aligned, scaled, and rotated.

```
(* Minimal example *)
plot = Plot[1 - Exp[-x], {x, 0, 3}, AxesLabel -> {"xlabel", "ylabel"}];
(* Export into eps format *)
Export["plot.eps", plot];
```

- Inside $\LaTeX$ document, do:

```
\documentclass{article}
\usepackage{graphicx, psfrag}
\begin{document}
\begin{figure}
\psfrag{xlabel}{thickness $\mu m$}
\psfrag{ylabel}{power density $W/m^2$}
\includegraphics{plot.eps}
\end{figure}
\end{document}
```

- Without doing above hassle, there is a Mathematica package called MathPSfrag to do the same thing in one go. But, it’s outdated and you need to fix the bug by yourself.
- Another promising Mathematica package is SciDraw.

### Statistics of list of unequal length lists

- We are interested to find the mean and standard deviation of the “list of lists” of its columns.

```
(* If the inner lists has equal lengths then, we can simply do: *)
goodlistoflists = Table[Table[RandomReal[i], 5], {i, 10, 50}];
Mean[goodlistoflists]
(* But, if the inner lists have unequal lengths, then, we need to do: *)
(* Let's create a list of lists where inner lists length is not same. This means, we cannot simply say our list of lists is a matrix, and thus cannot able to know the no. of columns *)
badlistoflists = Table[Table[RandomReal[i], RandomInteger[{4, i}]], {i, 10, 50}];
(* In-order to take a mean of listoflists, we define our custom Mean function: *)
MeanUnEqualLength[data_] := (
m = {};
i = 1;
While[True,
meani = Query[Mean]@Query[All, i]@data;
If[ToString[meani] != ToString[Mean[{}]],
AppendTo[m, meani]; i++,
Break[]];
];
Return[m]
)
(* Now, we should be able to get the Mean's easily *)
MeanUnEqualLength[badlistoflists]
(* Lets check if using Mean[] and MeanUnEqualLength[] gives the same answer for the list "goodlistoflists" *)
Mean[a] === MeanUnEqualLength[a] (* Output: True *)
(* To calculate the standard deviation, we define our custom function: *)
StandardDeviationUnEqualLength[data_] := (
s = {};
i = 1;
While[True,
ready = DeleteCases[Query[All, i]@data,
Missing["PartAbsent", i]] ;
If[Length[ready] != 0,
AppendTo[s, Query[StandardDeviation]@ready]; i++,
Break[]];
];
Return[s]
)
(* Check if using StandardDeviation[] and StandardDeviationUnEqualLength[] gives the same answer for the list "goodlistoflists" *)
StandardDeviation[goodlistoflists] === StandardDeviationUnEqualLength[goodlistoflists] (* Output: True *)
```

### Time consumed by some cells

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

### 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 making visible again:

```
OpenAllInputsCells[] := Module[{nb, cells},
nb = EvaluationNotebook[];
cells = Cells[nb, CellStyle -> "Input"];
SetOptions[#, CellOpen -> True] & /@ cells;
];
```

- How to use it?

- Copy / Paste both functions above in a fresh / new notebook and run the notebook.
- Inside your target Notebook, at the end of your document, run CloseAllInputsCells[] . All input cells will be closed.
- For recovering all inputs again, run OpenAllInputsCells[]

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

## Quick Hacks

```
ToExpression@StringReplace[ToString@HoldForm[{1.05335, 1.05335 e - 06, 1.05335 e - 06}], "e" -> "*10^"] (* Convert list of E notations to list of scientific notations *)
data = {0, Indeterminate, -\[Infinity], 15.4709, -16.3311, 17.833, -17.0255};
Max@Cases[data, Except[Indeterminate]] (* Find the maximum value in data array excluding indeterminate *)
ToExpression@Import["textfilename.nb","Text"] (* Importing and evaluating notebook from plain text *)
(* Make pairs two arrays*)
x = {1, 2 , 4, 5}
y = {1, 4, 16, 25}
xy = Transpose[{x, y}] (* Or you can also do: Transpose@{x, y} *)
(* Convert HTML HEX color code to Mathematica RGBColor *)
ResourceFunction["HexToColor"] /@ {"5E81B5", "#FF9C24", "#8FB131", "#EC6235"}
(* Convert RGBColor to HTML HEX color code *)
ResourceFunction["ColorToHex"] /@ {RGBColor[0.372549, 0.505882, 0.709804], RGBColor[1, 0.611765, 0.141176]}
```

Permalink athttps://www.physicslog.com/cs-notes/mathematica

Published onNov 23, 2021

Last revised onAug 12, 2023

References

- Official Mathematica Docs
- Mathematica Stack Exchange
- Fast introduction for Programmers
- The Mathematica® Journal
- Functional Programming
- Shorthand Notations
- Keyboard Shortcut
- Mathematica cells in $\LaTeX$ document
- More on SameQ
- List Manipulation
- $\LaTeX$ typesetting in Mathematica using MaTeX
- Display the Timing of an Evaluation
- Use Do loop instead of For loop
- Span (or slicing) the array
- Collections related to Mathematica
- General Graph Drawing