How to Mathematica

A practical guide for using Mathematica in problem sets

Ben Bartlett - Ruddock ‘17
2017 Ruddock Upperclassman Workshop: 24 April, 9pm

Contents:

0. Wolfram documentation

1. Formatting a notebook

Cell styles

Cell styles as folders

Math input

Suppressing output

Greek characters

Simple operator input

More complex operator input

2. Prerequisites: variables, functions, rule replacements, prefixes/suffixes, and lists

Variables

Using results from previous cells

Functions

Pattern matching in functions

Rule replacements

Prefixes and suffixes

Lists

3. Commonly-used things in Mathematica

Copy results to MathematicaGuide_1.png

Simplifying expressions with FullSimplify[]

Solving equations with Solve[]

Solving differential equations with DSolve[]

Free-form and Wolfram|Alpha input

Should I use Mathematica as a Wolfram|Alpha client?

Using free-form input in standard input cells

Working with units

Solving numerically with NSolve[] and NDSolve[]

Application: using boundary conditions

Working with vectors and matrices

Fitting functions to data

LinearModelFit[]

NonlinearModelFit[]

4. Plotting relationships and data in Mathematica

Plotting symbolic relationships with Plot[]

Plotting lists with ListPlot[]

Other common types of plots

Using Manipulate[]

MathematicaGuide_2.gif

0. Wolfram documentation

Mathematica has incredibly well-documented functionality. Typing any command in an input cell and hovering over the text with your mouse will bring up a dropdown menu linking to the documentation for that command. The Wolfram Language Documentation Center also has a series of excellent video tutorials that cover a lot of introductory topics to using Mathematica.

1. Formatting a notebook

Mathematica is frequently used as a scratchpad for calculations, producing messy output that needs to be inserted into a more cleanly typed problem set. However, Mathematica documents can formatted with text, images, and other media to produce well-organized content that is suitable to turn in as a problem set!

Cell styles

Using Format -> Style, (Alt + number on Windows or Cmd + number on Mac) you can change the style of a cell to make a title, subtitle, section, subsection, or text. There are a lot of options for this, but the only ones really worth remembering are (replace Alt with Cmd for Mac):

Title: Alt + 1 (Cmd + 1 on Mac)

Chapter: Alt + 2

Section: Alt + 4

Subsection: Alt + 5

Text: Alt + 7

Cell styles as folders

Mathematica also groups cells by descending section order. This allows you to collapse entire sections that you don’t need to look at. If you hover over the extended right bracket “]” spanning this section, it will turn blue. Double click it to collapse the section, and double click again to expand it again.

Try it yourself

Try changing the style of this cell to a subsection!

Math input

One of the first things that turns new people off from Mathematica is the ugly way that expressions can look when you write them down. For example,

MathematicaGuide_3.png

MathematicaGuide_4.png

is not the most easily readable expression. However, using the correct keyboard input, you can write this much more nicely:

MathematicaGuide_5.png

MathematicaGuide_6.png

If you’re just starting out using Mathematica, you might find the math palettes (Palettes -> Basic Math Assistant) useful.

MathematicaGuide_7.gif

MathematicaGuide_8.gif

Hovering over any of the buttons should display the keyboard shortcut to enter that expression in Mathematica. Learn these! They’ll save a lot of time in the future.

There is a lot of functionality here, but as usual with this guide, I’ll cover the ones most useful to know.

Suppressing output

When you evaluate a cell with Shift+enter, you’ll see an input and an output. Sometimes, for example if you’re defining a block of variables, you don’t need this output. In this case, you can suppress the output with a semicolon.

MathematicaGuide_9.png

MathematicaGuide_10.png

MathematicaGuide_11.png

Greek characters

Any Greek character can be input into a document (in text mode or input mode) by typing esc+letter+esc. For example, esc+p+esc inputs π, esc+G+esc gives Γ, and esc+b+esc is β. This alone can easily reduce a lot of the ugliness associated with Mathematica syntax in a notebook. A few other useful similar shortcuts:

esc + ii + esc: i (imaginary number)

esc + ee + esc: e (number e)

esc + inf + esc: ∞

Simple operator input

Many common operators can be written in Mathematica using Ctrl+key (on both Windows and Mac - not Cmd). These are typically pretty easy to remember:

Ctrl + / gives a fraction: MathematicaGuide_12.png

Aside: multiplication is done by *, but can be implicitly used by simply putting a space between two variables

Ctrl + 2 gives a square root: MathematicaGuide_13.png

Ctrl + 6 gives an exponent: MathematicaGuide_14.png

Ctrl + 9 opens an inline math cell (only in text mode!): MathematicaGuide_15.png

Ctrl + - creates a subscript: MathematicaGuide_16.png

As a general rule, I wouldn’t recommend naming any of your variables with subscripts, since Mathematica has inconsistent handling of variables with subscripts in them. I always convert MathematicaGuide_17.png to “xi” in my code.

As usual, there are many others, but these are some of the most commonly used ones.

More complex operator input

Mathematica also has a lot of “template operators” that typeset nicely in a notebook. These are typically entered by esc + (some sensible shortcut) + t + esc. For example:

esc + intt + esc is an indefinite integral: ∫■d

esc + dintt + esc is a definite integral: MathematicaGuide_18.png

esc + sumt + esc is a sum: MathematicaGuide_19.png

esc + prodt + esc is a product: MathematicaGuide_20.png

These can be nested too! For example,

MathematicaGuide_21.png

MathematicaGuide_22.png

Some operators aren’t templated, but are entered in a similar way:

esc + dd + esc is a differential symbol: d

This one is tricky - this isn’t the same as D[expr, var]. For that, you need to use the ∂ symbol

esc + pd + esc is a partial differential symbol: ∂

You can use this in place of D[expr, var]:

MathematicaGuide_23.png

MathematicaGuide_24.png

Try it yourself

Try entering the Ramanujan approximation of π in a new cell below.

2. Prerequisites: variables, functions, rule replacements, prefixes/suffixes, and lists

Mathematica has most data structures of other programming languages, but for use as a calculation tool for non-CS problem sets, there’s only a few that you have to know.

Variables

Variables in Mathematica can have two “types” (note that Mathematica is completely untyped, so I use this word in the loosest sense): symbolic or defined. Symbolic variables will always be blue or green in the document (they’re green if they’re used for evaluating something, like in plotting), while defined variables, which can be either expressions of symbolic variables or numbers, are black. You can clear defined variables using Clear[var1, var2, var3...]

Using results from previous cells

You can use previously computed results either by storing them to a variable (usually preferred) or by using the % operator, which gets the last Out[] result computed in the notebook. Note: this is the last value computed, not necessarily the previous cell!

MathematicaGuide_25.png

MathematicaGuide_26.png

MathematicaGuide_27.png

MathematicaGuide_28.png

Using %%...% gets the (number of %’s) previous cell:

MathematicaGuide_29.png

MathematicaGuide_30.png

MathematicaGuide_31.png

MathematicaGuide_32.png

And using %n or Out[n] uses the n’th output:

MathematicaGuide_33.png

MathematicaGuide_34.png

Functions

Built-in Mathematica functions always start with a capital character. You can also define your own functions. Mathematica admits two types of “functions”. You can define variables to be “expressions” of symbolic variables with an = symbol, or you can define formal functions that use lazy evaluation using a transformation rule on a symbol (x_, for example), and a := symbol. For example:

MathematicaGuide_35.gif

MathematicaGuide_36.png

MathematicaGuide_37.gif

MathematicaGuide_38.png

Pattern matching in functions

You can use existing symbols to create inferred functional patterns. For example, if I wanted to define the tensor product of two vectors (typically denoted by KroneckerProduct[v1, v2]) using the standard ⊗ notation, I could use:

MathematicaGuide_39.png

MathematicaGuide_40.gif

MathematicaGuide_41.png

Rule replacements

Mathematica is a functionally-styled programming language, and has nice rule replacements. You can replace any symbol in an expression with another expression by using a rule replacement: “/.”

MathematicaGuide_42.png

MathematicaGuide_43.png

MathematicaGuide_44.gif

MathematicaGuide_45.png

Prefixes and suffixes

These aren’t terribly important, but can save you time typing and make your input look more nicely formatted. You can add a prefix or suffix to any function by using the @ and // operators, respectively. These work with any function that takes only a single argument. For example:

MathematicaGuide_46.png

MathematicaGuide_47.png

MathematicaGuide_48.png

MathematicaGuide_49.png

MathematicaGuide_50.png

MathematicaGuide_51.png

Lists

Lists in Mathematica are simply collections of items (that don’t have to be of the same type) and are handled similarly to Python, with a few exceptions. They are entered using curly braces: {item1, item2, item3}.

MathematicaGuide_52.png

Lists are 1-indexed (important!) and can be sliced with the [[ ;; ]] operators:

MathematicaGuide_53.png

MathematicaGuide_54.png

MathematicaGuide_55.png

MathematicaGuide_56.png

MathematicaGuide_57.png

MathematicaGuide_58.png

You can also generate lists with a Table[] function:

MathematicaGuide_59.png

MathematicaGuide_60.png

MathematicaGuide_61.png

MathematicaGuide_62.png

There are a lot of other list manipulation functions available in the documentation.

3. Commonly-used things in Mathematica

Mathematica can be an indispensable tool for use in your problem sets. Although the language has basically everything you could ever think of built in as dedicated functions, you’ll find yourself using a handful of functions fairly often. I’ll cover these below.

Copy results to MathematicaGuide_63.png

If you use MathematicaGuide_64.png to type up your problem sets, you can copy results from Mathematica output by selecting the desired output and selecting “Copy As -> MathematicaGuide_65.png".

Simplifying expressions with FullSimplify[]

There’s a lot of built-in simplification functions and expression manipulation functions (Expand[], Factor[], Together[], etc.), but the go-to function is always FullSimplify, which will get you the result you want about 80% of the time, anecdotally.

MathematicaGuide_66.png

MathematicaGuide_67.png

MathematicaGuide_68.png

MathematicaGuide_69.png

You can also use FullSimplify to verify solutions satisfy an equation

MathematicaGuide_70.png

MathematicaGuide_71.png

MathematicaGuide_72.png

MathematicaGuide_73.png

Solving equations with Solve[]

Solve[] lets you solve an algebraic equation or system of equations for possible solutions. Note that when using Solve[] (or any other similar function, like NSolve, DSolve, etc), you need to use the test equality operator == rather than the assignment operator =, just like you would in Python. Solve[] gives a list of rule replacements, not a list of solutions, so if you want to assign something to a value from Solve, you need to destructure the list (First[] and Last[] are frequently helpful here) and apply the corresponding rule replacement to isolate the variable.

MathematicaGuide_74.png

MathematicaGuide_75.png

MathematicaGuide_76.png

MathematicaGuide_77.png

MathematicaGuide_78.png

MathematicaGuide_79.png

MathematicaGuide_80.png

MathematicaGuide_81.png

MathematicaGuide_82.png

MathematicaGuide_83.png

Solving differential equations with DSolve[]

DSolve[] works very similarly to Solve[], except that it requires initial conditions in some cases. (As of Mathematica 10, there’s also a handy function to retrieve the solutions, rather than rule replacements, from DSolve, which is the wrapper function DSolveValue[].) When typing the equations, use ‘ to denote derivatives with respect to the independent variable.

MathematicaGuide_84.png

MathematicaGuide_85.png

MathematicaGuide_86.gif

MathematicaGuide_87.gif

MathematicaGuide_88.png

MathematicaGuide_89.png

MathematicaGuide_90.gif

MathematicaGuide_91.png

Free-form and Wolfram|Alpha input

As of Mathematica 8, you can use “free-form input” to express what you want to do in natural language. Mathematica is generally pretty good at figuring out what you’re trying to do. It also allows an extension of this: free-form Wolfram|Alpha input.

To use free-form input, press “=” in any blank code cell to switch it to free-form mode. Pressing “=” again will switch it to Wolfram|Alpha input, and pressing “=” a third time cycles it back to normal input. The use of both input styles is shown below.

MathematicaGuide_92.gif

MathematicaGuide_93.png

In[50]:=

integrate 5x^2 from x=2 to x=5

Should I use Mathematica as a Wolfram|Alpha client?

Probably not. Mathematica can be a challenging platform to learn, and it’s alright to use Wolfram|Alpha if you don’t know how to do something, but, in my experience, Wolfram|Alpha stops being useful for physics problem sets around sophomore year. There are a tremendous number of things Mathematica can do that Wolfram|Alpha simply can’t, and you will eventually see some of those things appearing in your problem sets.

Using free-form input in standard input cells

If you press Ctrl+“=” (on both Windows and Mac), you can enter a small portion of free-form input in a portion of a standard input cell. This is extraordinarily useful when working with units! (See later in this section for working with units.) For example,

MathematicaGuide_95.png

MathematicaGuide_96.png

Working with units

Mathematica has an excellent and robust units system. The formal command for using units is Quantity[]:

MathematicaGuide_97.png

MathematicaGuide_98.png

However, the easiest way to input units, and the way I almost always use, is with free-form input using Ctrl+“=”.

MathematicaGuide_99.png

MathematicaGuide_100.png

Using UnitConvert[], you can convert some arbitrary expression into any equivalent set of units. Or, more frequently, you’ll just want to convert it to SI:

MathematicaGuide_101.png

MathematicaGuide_102.png

MathematicaGuide_103.png

MathematicaGuide_104.png

You can also look up a huge amount of quantitative data using free form input! For example, using “gravitational constant”, “earth mass”, and “earth radius” in free-form input boxes, I can calculate the surface acceleration of the Earth:

MathematicaGuide_105.png

MathematicaGuide_106.png

Solving numerically with NSolve[] and NDSolve[]

As you probably know, many differential equations are not analytically solvable (and some algebraic equations are gross), so you can use Mathematica’s built-in numerical solvers to work with these types of equations. NSolve[] works almost exactly the same as Solve[]:

MathematicaGuide_107.png

MathematicaGuide_108.png

When using NDSolve[], you’ll get a numerical “InterpolatingFunction” as an output:

MathematicaGuide_109.png

MathematicaGuide_110.gif

You can use this InterpolatingFunction exactly as you would a regular function:

MathematicaGuide_111.png

MathematicaGuide_112.gif

Application: using boundary conditions

As of Mathematica 10, it allows you to input Neumann and Dirichlet boundary conditions when numerically solving differential equations! For example, this is the solution to the potential throughout a metal plate with current passing through it via wires attached at the midpoints of the short end:

MathematicaGuide_113.gif

Graphics:Electrostatic potential in a current-carrying conductive plate

Working with vectors and matrices

Matrices in Mathematica work the same way they do in Python, except with the changes you’ve already seen for how vectors work. You can make matrices as lists of lists:

MathematicaGuide_115.gif

There are lots of matrix operations you can do. For example, you can transpose a matrix and display it like it would be written on paper:

MathematicaGuide_116.png

MathematicaGuide_117.png

You can find the eigenvectors and eigenvalues of a matrix:

MathematicaGuide_118.png

MathematicaGuide_119.png

You can multiply matrices and vectors together with the “.” operator:

MathematicaGuide_120.png

MathematicaGuide_121.png

And you can retrieve the magnitude of a vector with Norm[]:

MathematicaGuide_122.png

MathematicaGuide_123.png

Lots of vector calculus operations will require you to work with vectors and matrices. For example, you can take the curl of a vector field in Mathematica:

MathematicaGuide_124.png

MathematicaGuide_125.png

You can also do this using esc+delx+ esc to make a nice pretty template:

MathematicaGuide_126.png

MathematicaGuide_127.png

Mathematica also allows for very easy coordinate changes. For example, you can take the curl of something in spherical coordinates:

MathematicaGuide_128.png

MathematicaGuide_129.png

Fitting functions to data

Although it isn’t the program’s primary purpose, Mathematica includes a lot of statistical manipulation functions. The most commonly used of these, in my experience, is the fitting functions LinearModelFit[] and NonLinearModelFit[]. Let’s try these out:

LinearModelFit[]

MathematicaGuide_130.gif

MathematicaGuide_131.png

MathematicaGuide_132.png

MathematicaGuide_133.png

MathematicaGuide_134.png

MathematicaGuide_135.gif

MathematicaGuide_136.png

MathematicaGuide_137.gif

We can do more complex stuff with LienarModelFit[] too, like fitting data to multiple variables:

MathematicaGuide_138.gif

MathematicaGuide_139.png

Or fitting data to functions of variables:

MathematicaGuide_140.png

MathematicaGuide_141.png

NonlinearModelFit[]

Sometimes you get data that depends on some functional forms of variables. For example, if we considered “noisy” radioactive decay:

MathematicaGuide_142.gif

MathematicaGuide_143.gif

You can fit this type of data to a model using NonlinearModelFit[] and specifying the desired form of the data along with the constants to solve for. For example, in this case, we know decay rate follows MathematicaGuide_144.png, so we can do:

MathematicaGuide_145.png

MathematicaGuide_146.png

MathematicaGuide_147.png

MathematicaGuide_148.gif

4. Plotting relationships and data in Mathematica

Plotting symbolic relationships with Plot[]

Mathematica’s plotting functionality is the easiest to use and most robust of any library I’ve come across. Plot[] is your bread-and-butter function here, and can be used to plot arbitrary symbolic relationships:

MathematicaGuide_149.png

MathematicaGuide_150.gif

You can also use Plot[] with lazily-defined (:=) functions:

MathematicaGuide_151.gif

MathematicaGuide_152.gif

You can add legends with the option PlotLegends, axes labels with AxesLabel, and many other possibilities available in the documentation.

MathematicaGuide_153.png

MathematicaGuide_154.gif

Plotting lists with ListPlot[]

ListPlot[] works similarly to plot, but on lists of data rather than functional relationships. For example:

MathematicaGuide_155.png

MathematicaGuide_156.gif

Other common types of plots

Other useful plot functions include ContourPlot[], Plot3D[], ListContourPlot[], and ListPlot3D[]. Extensive documentation is available for these functions, so I’ll just demonstrate one of each:

MathematicaGuide_157.png

MathematicaGuide_158.gif

MathematicaGuide_159.png

MathematicaGuide_160.gif

MathematicaGuide_161.png

MathematicaGuide_162.gif

MathematicaGuide_163.png

MathematicaGuide_164.gif

Using Manipulate[]

This is one of my favorite features of Mathematica: using Manipulate[], you can create interactive plots that allow you to explore the behavior of something as a function of some input variable(s). For example:

MathematicaGuide_165.png

You can do a lot of really cool things with this. For example, here’s a plot of the equipotential lines from two charge sources: (you can adjust the sliders to adjust the magnitude of the charges and drag the positions of the charges around in the plot)

MathematicaGuide_167.png

And here’s a manipulable solution to the Rossler attractor (a set of chaotic differential equations) displaying the behavior of all component coordinates:

MathematicaGuide_169.gif

MathematicaGuide_170.gif

Created with the Wolfram Language