Brief Introduction to Mathematica

author:

Alan G. Isaac

organization:

American University

copyright:

2022-01-10

Background

What Is Mathematica?

Mathematica is commercial software. It is popular among economists because it is a complete computer algebra system, enabling symbolic as well as numerical computation. Additionally, it includes excellent notebook facilities.

Mathematica is a computer algebra system built around the Wolfram Language, which fully supports symbolic computation and array operations. A value in Mathematica is always an expression, and operations on expressions typically have no addtional data type expectations. (If an operation encounters an expression it does not know how to manipulate, it simply leaves in unevaluated.)

The Mathematica REPL

There is a very limited text-based environment that allows REPL-like access to the Mathematica kernel. Most users will prefer to work with Mathematica notebooks in order to take advantage of their display capabilities and convenient navigation.

Mathematica from the Command Line

The wolfram and wolframscript executables can run Mathematica programs from the command line. The latter can execute code snippets from your operating system’s command shell.

wolframscript -code (2+2)

https://reference.wolfram.com/language/workflow/RunWolframLanguageCodeFromTheCommandLine.html

Getting Help

Start up a new Mathematica notebook (e.g., by double-clicking the program icon). In the new notebook, start typing. This opens a new input cell. Type a question mark followed by a command. For example, to access the help for Mathematica’s mathematical constant Pi as follows.

?Pi

After typing this in an input cell, display the basic help for the command by pressing [shift]+[enter]. This evaluates the expression in the input cell. Exit the program as usual.

Interactive Hello World

In a Mathematica notebook enter Print["Hello World!"] in an input cell, followed by [shift]+[enter]. This prints the string.

Hello World Script

Create a folder for your Mathematica experiments. In this folder, create a file named HelloWorld.wl that contains this single line:

Print["Hello World!"]

In your shell, change to your project directory. Enter wolframscript -file HelloWorld.wl, and you should see the expected result print out in your shell.

Next, start the Mathematica REPL in the folder containing this file. Enter the following at the REPL command line, and you should see the expected result print out in the REPL.

Get["HelloWorld.wl"]

Video: The All-New Wolfram Script

Documentation: Create Wolfram Language Scripts and WolframScript (for the Command Line).

Older Conventions for File Execution

The relatively new wolframscript binary sits alongside the traditional math and wolfram binaries. Consider math to be a deprecated alias for wolfram; the binaries appear to be identical. The wolframscript binary offers a superset of the capabilities of wolfram, including simple execution in the cloud. However, all we care about right now is wolframscript -file file vs wolfram -script file. These are roughly equivalent as long as you have a single version of Mathematica (or the EngineJ) installed. Related to this, the extensions .m, .wl, and .wls are all in use. We will use only the .wl extension.

https://reference.wolfram.com/language/ref/program/wolfram.html https://reference.wolfram.com/language/ref/program/wolframscript.html

Basic Syntax

Basic syntax: https://reference.wolfram.com/language/guide/Syntax.html

Key surprises: use a backtick instead of an underscore to separate parts of variable names. The percent sign (%) is not the remainder operator.

Arithmetic

Arithmetic operators are pretty standard, except that exponentiation uses the caret (^). The most surprising thing is that operators represent equivlanet functions.

1+2+3       (* 6 *)
Plus[1,2,3] (* 6 *)

One other surprising behavior is the support for implicit multiplication, as in Julia. (This is convenient in the REPL, but do not use it in your code.)

x=3
2 x    #6

Use Quotient[m,n] for integer division; it produces the greatest integer less than m/n. In Mathematica, % is special; it is not the remainder operator. Use Mod[m,n] for the remainder from integer division. Produce both the divisor and the remainder with QuotientRemainder.

Make immediate assignments with the = operator. Make delayed assignments with the := operator. Test equality with the == operator or the Equal function. Test identity with the === operator or the SameQ function. (See the documentation for details.)

Mathematica provides a very large collection of builtin functions. Mathematica’s support for broadcasting is powerful but somewhat idiosyncratic. Pay particular attention to Thread and MapThread.

Numbers

Mathematica allows computing with many different number types, but also allows you to ignore this capability when you wish. The Protect function allows you to prevent changes to the value associated with a symbol.

https://reference.wolfram.com/language/ref/Protect.html

Random Numbers

The RandomReal and RandomInteger functions are builtin. To seed them, use SeedRandom or BlockRandom.

SeedRandom[314]
RandomInteger[{0, 5}, 5]  (* {5, 2, 0, 4, 5} *)
BlockRandom[
 RandomInteger[{0, 5}, 5],
 RandomSeeding -> 314]    (* {5, 2, 0, 4, 5} *)

Compound Expressions

Using semicolons, a sequence of expressions may be chained into a compound expression, which has the value of the last expression. (Or, use the CompoundExpression command.)

z = (x = 0; y = 1; x + y)           (* 1 *)
z = CompoundExpression[x=1,y=2,x+y] (* 1 *)

This is sometime called chain syntax, and it may span multiple lines.

z = (x = 0;
     y = 1;
     x + y)

Warning: Compound expressions do not establish a new variable scope. You can use With instead.

z = With[{x = 0,y = 1}, x + y]

Ordinary Function Definition

Ordinary function definition uses the Function command (or equivalent shorthand notation). There is Return command, but its use is optional. In the absence of a Return, the value of the function is the value of the last expression in the function body.

test = Function[x, 1+x]

There is a very terse equivalent shorthand syntax, which is convenient for short functions:

test3 = (1 + #)&

To introduce variables a function body that are local to the function, use With or Module. In Mathematica, functions are first class objects. They can be passed around like any other object.

Function Arguments

Pattern-based function definitions can include ordinary arguments or keyword arguments. Keyword arguments are defined as options (and must have default values).

Composition and Piping

Mathematica uses a @* for ordinary composition: \(f @* g\) produces the ordinary composition of two functions, such that \((f @* g)[x]==f[g[x]]\). The same effect is produced by piping: x // g // f.

Operator Forms

Many Mathematica commands have an operator form.

Map[#^2&, {1,2,3}]
Map[#^2&][{1,2,3}]  (* equivalent with operator *)

Control Flow

Mathematica’s boolean values are True and False. Conditional branching is done with If syntax.

If[x < y,
  Print[x," is smaller than ", y],
  Print[x," is not smaller than ", y]
]

Variables and Scope

A variable can have local or global scope. Here global means in the Global context. Variables are typically lexically scoped, so the meaning of a nonlocal variable in a function is determined by the scope in which the function definition occurs, not the scope from which it is called. There is no substitute for Mathematica’s documentation of scoping constructs.

Atomic and Composite Types

todo

Constructors for Composite Types

todo

You may define a constructors to create a composite type.

newPoint[x_Integer,y_Integer] := point[N@x, N@y]

pt = newPoint[1,2]  #point[1.0,2.0]

This example is rather pointless (pun intended).

Packages

Plotting

Mathematica’s plotting capabilities are extensive and simple to use. In a notebook, produce a run-sequence plot or line-plot as follows.

plt1 = ListPlot[{1,2,3}]
plt2 = ListLinePlot[{1,2,3}]

If you creat several plots, you can plot them together.

Show[plt1, plt2]

Use GraphicsRow, GraphicsColumn, or GraphicsGrid to control the layout of multiple plots.

Labeled Scatter Plots

todo

Some Mathematica Resources

Introductory Materials

Video: Mathematica Basics by Jon McLoone

https://www.youtube.com/watch?v=ugRuESa_cu0

An Elementary Introduction to the Wolfram Language (by Stephen Wolfram)

Mathematica Introduction

https://subversion.american.edu/aisaac/notes/mmaPart1.pdf (Please report typos!)

Introductory Videos

Hands-on Start to Mathematica

by Cliff Hastings

Mathematica For Beginners: The Basics

by Richard Southwell https://www.youtube.com/watch?v=Zp1EV7ytSnA

Importing Data into Mathematica

by Ben Zwickl http://www.youtube.com/watch?v=MmS3JNk7JE4 (his other videos are also good).

Introductory Books

An Elementary Introduction to the Wolfram Language

[Wolfram-2017-WolframMedia] is free online.

The Student's Introduction to Mathematica and the Wolfram Language

[Torrence.Torrence-2019-CambridgeUP] is a mathematically oriented introdution to Mathematica. Chapter 1 and 2 provide a gentle introduction to the language. Chapter 8 provides a good overview of Mathematica programming.

A Few Intermediate Books

An Introduction to Modern Mathematical Computing: With Mathematica

Borwein, Jonathan M. and Matthew P. Skerritt (ISBN: 978-1-4614-4252-3)

Wolfram Virtual Book

https://reference.wolfram.com/language/tutorial/VirtualBookOverview.html

Practical Optimization Methods: With Mathematica Applications

by M. Asghar Bhatti; Springer (2000) ISBN-13 978-0387986319

Multivariable Calculus with Mathematica 1st Edition

by Robert P. Gilbert, Michael Shoushani, Yvonne Ou; Chapman and Hall/CRC; 1st edition (November 25, 2020) ISBN-13 978-1138062689

A Few Advanced Books

Mathematica Programming: An Advanced Introduction

[Shifrin-2009-Self] (free online at http://www.mathprogramming-intro.org/).

Modeling naturecellular automata simulations with Mathematica

Gaylord, Richard J. and Kazume Nishidate isbn 0387946209

Modern Differential Geometry of Curves and Surfaces with Mathematica 3rd Edition

by Elsa Abbena, Simon Salamon, Alfred Gray; Chapman and Hall/CRC; 3rd edition (June 21, 2006) ISBN-13 978-1584884484

References

[Shifrin-2009-Self]

Shifrin, Leonid. (2009) Mathematica Programming: An Advanced Introduction. : self published. http://www.mathprogramming-intro.org/

[Torrence.Torrence-2019-CambridgeUP]

Torrence, Bruce F., and Eve A. Torrence. (2019) The Student's Introduction to Mathematica(R): A Handbook for Precalculus, Calculus, and Linear Algebra. : Cambridge University Press.

[Wolfram-2017-WolframMedia]

Wolfram, Stephen. (2017) An Elementary Introduction to the Wolfram Language. Champaign, IL: Wolfram Media. https://www.wolfram.com/language/elementary-introduction/2nd-ed/