Mathematica - Additional Information

What is Mathematica?

Mathematica is a general computer software system and language intended for mathematical and other applications. Mathematica is used as:

  • a numerical and symbolic calculator where you type in questions and Mathematica prints out answers.
  • a visualization system for functions and data.
  • a high level programming language in which you can create programs, large and small.
  • a modeling and data analysis environment.
  • a system for representing knowledge in scientific and technical fields.
  • a software platform on which you can run packages built for specific applications.
  • a way to create interactive documents that mix text, animated graphics and sound with active formulas.
  • a control language for external programs and processes.
  • an embedded system called from other programs.

Mathematica computations can be divided into three main classes: numeric, symbolic and graphical. Mathematica handles these three classes in a unified way. Mathematica uses symbolic expressions to provide a very general representation of mathematical and other structures. The generality of symbolic expressions allows Mathematica to cover a wide variety of applications with a fairly small number of methods from mathematics and computer science.

The simplest way to use Mathematica is like a calculator. You type in a calculation and Mathematica prints out the answer. The range of calculations that you can do with Mathematica is however far greater than with a traditional electronic calculator or even with a traditional programming language such as BASIC or Fortran. For example, while a traditional system might support perhaps 30 mathematical operations, Mathematica has over 750 built in. In addition, while traditional systems handle only numerical computations, Mathematica also handles symbolic and graphical computations.

Starting Mathematica

To start Mathematica, enter mathematica at the UNIX prompt. Mathematica documents are called notebooks. When you start Mathematica, an empty notebook window appears on your screen, you can enter input to be evaluated by the mathematica kernel. As soon as you start typing, a cell is created and indicated by a cell bracket along the right edge of the notebook window. Each piece of information in the notebook is contained in a separate cell. A cell can contain either explanatory text, kernel input or output, or graphics, but not combinations.

Mathematica does not automatically load the kernel when you start. To start the kernel, type your first expression (i.e. 2+2) and then press Shift-Return. This might take a while because Mathematica is a large program to load. If you eventually get an answer (4) you can assume things are working correctly and subsequent evaluations will occur much more quickly. Interaction with the kernel is similar to a "dialog". Text on the lines labelled In[n] := is what you type in; the lines labeled Out[n] = is what Mathematica prints back.

Mathematica can be run without using the X Front End. To run a text-based interface to interact with the Mathematica system (kernel) type math at the Unix prompt. To run a MathLink template file compiler type mcc at the Unix prompt.

Note: If you run Mathematica remotely, you must use "setenv DISPLAY local_IP_address:0.0" and not "setenv DISPLAY local_machine_name:0.0".

Getting Help From Mathematica 

Mathematica contains an extensive on-line information system. To get information about any menu command, press F1, and click on the menu command you want to know about with the question mark pointer. This will help you to learn about the "user interface" or front end. Help for Mathematica's functions can be obtained from the Function Browser in the help menu. This system explains Mathematica functions and allows you to evaluate the functions or paste them into cells. The help system is started by clicking on the help object in the upper right hand corner of the notebook. For detailed help, the Mathematica reference books are available in the Engineering Library.

There is a elp program available by typing mathbook at the UNIX prompt. Also, there are man pages available for commands.

Performing Calculations

To do a calculation, Mathematica sends input from the front end to the kernel, which evaluates the expression, and returns the result as output.

  1. Create a new cell by placing the cell insertion point in the Mathematica window.
  2. Type the expression you want to evaluate, for example, 5+7.
  3. Select the cell, then choose Evaluate Selection from the Action menu. You can also evaluate the expression by pressing Shift-Return, while the insertion point is in the cell or while the cell's bracket is selected.
  4. The result of the calculation appears in an output cell immediately below the input cell, and cell names are added to both the input and output cells.

If you need to abort an evaluation, choose Abort Calculation from the Interrupt submenu of the Action menu.

Enter the following expressions: (press shift-return after each entry)

	Expand[(1 + x)^10]
	Plot[Sin[x^2], {x, 0, 2Pi}]
	Plot3D[Sin[x] Sin[y], {x, 0, 2Pi}, {y, 0, 2Pi}]


To print a notebook, choose the Print or Print Selection command from the File menu, and set any necessary options in the Print dialog box that appears. The Print command prints the entire notebook, whereas the Print Selection command prints only those cells that are selected.

You can also change the appearance of your printed notebook by using options in the Printing Settings submenu.

Command Completion 

If you start typing the name of a Mathematica function, then choose the Complete Selection command from the Prepare Input submenu of the Action menu, the front end will help you complete the functions name.

  1. Type the first few letters: Int
  2. Choose Complete Selection

If there is only one possible completion, Mathematica automatically completes the selection at your insertion point; otherwise it lists other possible completions. Press Backspace or Delete to cancel.

Function Templates 

Another feature that helps you choose Mathematica input is the Make Template command, also in the Prepare Input submenu of the Action menu. When you choose this command with a Mathematica function selected or immediately before the text insertion point, Mathematica shows you an example of the function's use.

  1. Type the name of the Mathematica function: Plot3D
  2. Choose Make Template

You can now select each of the arguments and replace them with the values you want to use. This utility automatically uses Complete Selection if you type an incomplete or ambiguous function name.

Numerical Evaluation

The N function can be used to force Mathematica to give a numerical answer.

Five Basic Rules of Mathematica Syntax

  1. The arguments of functions are given in brackets [...]; parenthesis (...) are used for grouping operations; vectors, matrices and lists are given in braces {...}; and double square brackets [[...]] are used for indexing lists and tables.
  2. The names of built-in functions have their first letters capitalized; if a name consists of two or more words, the first letters of each word is capitalized.
  3. Multiplication is represented by a space or *.
  4. Powers are denoted by a ^.
  5. If you get no response or an incorrect response, you may have entered or executed the command incorrectly. In some cases, the amount of memory allocated to mathematica can cause a crash.

Creating Functions

    Defining Functions

A function is a transformation rule that specifies how  an argument is operated on. For example, consider creating a function "f" which squares its argument. The Mathematica command to define this function is " f[x_] := x^2 ". The "_" (referred to as "blank") on the left hand side is very important because it establishes the x as a generic expression holder and not something inherently connected to "x". In this example " f[x_] " is a transformation rule that specifies how the function "f" with any argument should be transformed.

    Functions As Procedures 

The functions you define in Mathematica are essentially procedures that execute the commands you give. A function can have many more operations than the simple one line function from above, by writing the function as a procedure. A procedure can be written in two ways as:

  1. A sequence of expressions to evaluate:

    func[var_list] := (expr1; expr2; ...)
  2. A procedure with local variables a, b, ...
    Module[{local_var_list}, expr_list]

When you write procedures in Mathematica, it is usually a good idea to make variables you use inside the procedure local, so they do not conflict or interfere with things outside the procedures. You can do this by setting up your procedures as modules, in which you give a list of variables to be treated as local to the procedure.

exprod[n_] := Expand[ Product[ x+i, {i, 1, n}]


   cex[n_, i_] := ( t = exprod[n]; Coefficient[t, x^i] )



   ncex[n_, i_] := Module[ {u}, u = exprod[n]; Coefficient[t, x^i]



Mathematica Packages

One of the most important features of Mathematica is that it is an extensible system. There is a certain amount of mathematical and other functionality that is built into Mathematica. But by using the Mathematica language, it is always possible to add more functionality. Many of Mathematica's specialized functions are not on-line when you first load the kernel but are available within a Mathematica Package. Mathematica packages are files written in Mathematica language and consist of collections of Mathematica definitions which "teach" Mathematica about a particular application area. If you want to use functions from a particular package, you must first read the package into Mathematica.

To load a package use <<name.



Now we could use the function Subfactorial as in:

In[5] := Subfactorial[10]

There are a number of subtleties associated with such issues as conflicts between names of functions in different packages, so be careful. One point to note, however, is that you must not refer to a function that you will read from a package before actually reading (loading) the package. If you do this by mistake, you will have to execute the command Remove ["name"]  to get rid of the function before you read in the package which defines it. If you do not call Remove, Mathematica will use "your" version of the function rather than the one from the package.

To find out what packages are available and what group of functions they contain, choose Open Function Browser from the Help menu and click on the Packages button. The Guide to Standard Mathematica Packages book is available as a reference book in the Engineering Library.


Notebooks are interactive documents that consist of a hierarchy of cells. Each cell contains a particular kind of material text, graphics, Mathematica input or output, and so on. Sequences of cells can be arranged in groups representing related material. A group of cells might, for example, correspond to a section or a chapter in your document.

The extent of each cell in a notebook is indicated by a bracket to its right. When you have a group of cells, another bracket shows the extent of the group. By looking at these brackets, you can see how a particular notebook is organized. When a group of cells corresponds to a section or a chapter of your document, the first cell in the group typically gives some kind of heading for the section or chapter. Notebook interfaces allow you to "close" groups of cells so that only their first cell is visible. If the first cells contain headings, you can get an outline of your document in this way.

An important feature of notebook interfaces is that they allow you to manipulate your document at several levels. At the lowest level, you can modify text or material within a single cell. At a higher level, you can do the same kinds of operations on a whole cell at a time. Beyond that, you can manipulate whole groups of cells. Notebook interfaces can take advantage of the typographical capabilities of the computer's graphical user interface. Thus, for example, cells containing text can have a variety of "styles." The style can involve various fonts, sizes and so on. In addition, even within a single cell you can mix several styles, allowing you to produce typographically complex text like you can with a word processor.

Notebook interfaces provide many options for displaying and importing graphics. One important feature is that you can take sequences of graphics cells, and "animate" them, treating each cell like a frame in a movie. The notebook interface allows you to set various parameters, such as speed and direction of your "movie." Another graphical feature is the ability to read coordinates from graphs using a mouse. You can also usually enter new points, whose coordinates you can get in textual form as Mathematica input.

Notebook Default Style Customization 

Place a copy of /usr/hp_apps/math/FrontEnd/ (on HPs) or /opt2/math/FrontEnd/ (on Suns) into your home directory. Go to the Edit menu and choose File Locations in the Preferences submenu and change the path of the Defaults notebook to your copy. Go to the Window menu and load Go to the Style menu choose Edit Styles, click the cells in the Styles dialog box you want to redefine, and then adjust their styles by using commands in the Formats menu. Now new notebooks will inherit the styles you selected.

Reading and Writing Files

You can use files on your computer system to store definitions and results from Mathematica. The most general approach is to store everything as plain text that is appropriate for input to Mathematica. With this approach the files can be manipulated by other standard programs, such as text editors.

Running Mathematica in Background

If you have a Mathematica program that is going to take a long time to run, you should run it in background on a DECS UNIX servers. See the following for instructions for running in this way.

  • The command is math < infile > outfile where 'infile' is a text file composed of the necessary Mathematica commands and the 'outfile' is the file that is written by Mathematica that contains the evaluations of each of the input commands. It is sometimes useful to make the first line in the 'infile' AppendTo[$Echo, "stout"] so that input lines will also be included in the output file.
  • To run this batch job in the background, execute the following command.
    nohup math < infile > outfile &

    This will continue running the batch job in the background even after you logout of your UNIX session.

  • If you have Mathematica commands stored in a notebook that you would like to transfer to your infile, you can use one of Mathematica's front end features to help you.
    1. Select the cell or set of cells that contain the commands you wish to be written to the infile text file.
    2. These cells will be deffined as initialization cells by clicking on Cell > Cell Properties > Initialization Cell in the menu bar.
    3. Now Mathematica can generate a text file by clicking on File > Save As Special.. > Package Format

    A dialog box will appear prompting you to give the file a name and location. You can use this Package Format file as the infile for your Mathematica batch job.

Initialization File

Every time Mathematica is started it reads the file named init.m. It will search for this file in your home directory and if it does not find it, it uses the one it finds in the file structure where Mathematica is physically located. This file is called a script and it contains Mathematica input that sets up the software for the necessary operating environment conditions. You can add Mathematica commands that will run every time you start Mathematica. To control your own start-up process, copy /opt2/math/StartUp/init.m into your home directory. Use a text editor to add the additional start-up commands. Please do not alter the text unless you very familar with the commands!

For instance, you could add the command:

$Path = Join[ $Path, "~/My_math_dir"]

to have your personal directory added to Mathematica's search path.

Things To Try

x^2 /. x -> 3
	g[x_, y_] := {Sin[x^2+y^2],Cos[y^2-x^2]}
	g[1, 2]
	h[x_] := 4x^3+6x^2-9x+2
	Plot[h[x], {x,-3,2}, AxesLabel -> {"x","h(x)"}, PlotLabel->{"Root Finding"}]