Mathematica Tips and Traps
  1. A Defensive Move
  2. Manipulating Input Regions
  3. Defining Variables
  4. Integers and Decimals are Not the same!
  5. Defining Functions
    1. Single Line Functions
    2. Multiple Line Functions
    3. Compiled Functions
  6. Defining Arrays
    1. One dimensional Arrays/Lists
    2. Multidimensional Arrays/Lists
    3. Generating Array/Lists
  7. Using Conditionals
  8. Defining Equations
  9. Graphics
    1. Plotting Functions
    2. Plotting Data Points
    3. Surface Plots
    4. Plotting Options
  10. Using Rules
  11. Turning Expressions into Functions
  12. Execution Speed
  13. Submit your own!

Physics Department Home Page Wong's Web Server Oberlin Online
Physics 240 Syllabus Wolfram's Home Page  Wolfram's Mathsource Page 
Mandelbrot Set Example Von Koch Snowflake Example Multipole Fields Example

A Defensive Move

Mathematica always remembers the everything that it has previously done in a session, including the values for variables. This is useful if you want to repeat a previous calculation using new values for the variables, but can cause major problems if you try to execute a notebook from the start and don't want the new values. Here is a way of making Mathematica "forget" everything you told it:

Always put this line as the first line in your notebook. Mathematica will complain the first time you run the notebook because it will say that it doesn't know anything to forget-just ignore it. Subsequent, executions of the notebook in that session will not produce an error message and Mathematica will "forget" everything that was done thus far (technically, it will remove them from the system). This will enable you to restart a calculation with a clean slate.

Note: It is good practice to re-execute the notebook from the start periodically. The reason is that often while trying to get Mathematica code to run correctly, the values of variables get changed without the programmer realizing it. With incorrect values stored, the algorithms may be correct but still produce erroneous results ("garbage in -garbage out"). Re-executing the notebook from the beginning will insure that the variables are set correctly. This is also how the graders and I will execute notebooks and judge their outputs-so always do a final execution of the whole notebook before turning anything in (make sure you have the above line installed!).

Go back to the Main Menu

Manipulating Input Regions

The vertical brackets on the side of the display indicate input and output regions. By clicking and highlighting a bracket, the entire region enclosed by it can be manipulated. The type of things that can be done include:

Go back to the Main Menu

Defining Variables

There are two ways to assign a value (numeric or symbolic) to a variable in Mathematica:

  1. x = a This assigns the present value of a to x. If the value of a changes later, the value of x is unaffected. As this method will greatly speed up calculations, it is the preferable method to use, as long as the value of a is completely determined at the time of the assignment to x.
  2. x := a This is a " delayed" assignment. This means that the value of a will not be given to x until x is used. This essentially establishes a relationship between the variables a and x. If the value of a changes later on, then the value of x will also change. This is much slower computationally than the other assignment method, so use it only in situations where you are trying to establish a generic relationship and not a transfer of values. Try rearranging the order in which variables are calculated to eliminate ":=" type assignments and reduce execution times.

Go back to the Main Menu

Integers and Decimals are Not the same!

Mathematica treats integers and decimals (values with a decimal point somewhere) differently. This is because integers are exact numbers and can be treated as such by the symbolic math processor. Operations such as Sqrt, etc are left unevaluated for integers because they have exact values. These unevaluated expressions are considered to be algebraic expressions by Mathematica and may have unexpected side effects on some operations, such as boolean opeations for conditionals, which are comparing expressions. Decimal inputs, however, are evaluated to approximate decimal values. To force Mathematica to evaluate integer values when execution speed is more important than alegraic accuracy, or numerical results are needed, use the N[] command.

For instance, compare:

Go back to the Main Menu

Defining Functions  
      f[time_, dfinal_, vfinal_] = Module[ {acc,v0, eq1, eq2,result},
        eq1 := vfinal== (1/2)*acc*time + v0;
        eq2 := dfinal == acc*time^2 + v0*time;
        result = {acc,v0} /.Solve[{eq1,eq2},{acc, v0}]; 
    1. These declare "local" variables that are only needed inside the function. Inside the function, local variables will always take precedence over any "global" variables with the same name. Local variables do not appear outside the function.
    2. Note the indentation. This is good programming practice and helps to visually separate the body of the function from its definition.
    3. The output of the function is the last line. Note the lack of the semicolon. You will get no output with a semicolon here.
    4. Note that this square brace is directly under its matching brace. This helps identify matching braces.
    Go back to the Main Menu

    Compiled Functions

    To create a function that is compiled for extra speed, use this format:

    f = Compile[ {x,y,z}, Module[

      --body of the module --

    Above, "f" is the name of the function, and x, y, and z are the input parameters to the function. the Module is the same as would appear in any multi-line function. For a single line function, the Module expression can be replaced with a single line expression as in an ordinary function.

    To specify a particular type of input parameter, use a numerical type identifier as such:

      g= Compile [{{a, _Real}, {b, _Complex}}, Module [ etc....
    If a function calls another function, compiling it does not always generate much increase in execution speed. Compiling a function seems to be the most effective when the function is totally self-contained.

    Go back to the Main Menu

Defining Arrays

    One dimensional Arrays/Lists

    Arrays are referred to as "lists" in Mathematica. A list can be declared as such:

    The elements of zlist can be accessed individually using double square brackets: Note how double square brackets are used to identify array elements, as opposed to the single square brackets used to identify the inputs to functions.

    Go back to the Main Menu

    Multidimensional Arrays/Lists

    A list can be made of lists. Here is a 2-dimensional array with 3 rows and 4 columns:.

    The rows can be accessed as a single entity: The trick is to remember that the element in the i'th row and j'th column in an array is really the j'th element in the i'th row of the array. Thus we do this to get z2D23: Go back to the Main Menu

    Generating Array/Lists

    Go back to the Main Menu

Using Conditionals

Mathematica is capable of perfoming conditional branching, where one set of instructions is executed when a certain condition is true and another set is executed when the condition is false. The basic syntax is the "If" statement:


condition_statement is an expression that evaluates to either "True" or "False". Examples: x>0, y<ymax, z==0, etc.

true_statements is a set of expressions to be executed if the condition_statement evaluates to "True". Each expression needs to be terminated with a semicolon.

false_statements is a set of expressions to be executed if the condition_statement evaluates to "False". Each expression needs to be terminated with a semicolon.

unknown_statements is a set of expressions to be executed if the condition_statement evaluates to neither "True" nor "False". Each expression needs to be terminated with a semicolon. This is essentially a fail-safe catch mechanism.

If you do not need one of the above statements, you may leave it blank, but be sure to put any necessary commas in to delineate where the statements are supposed to be.

Be careful when using conditional statements that involve operations on integer values, as unevaluated integer operations (See Integers and Decimals are Not the same!) appear as symbolic expressions and may not be processed by the conditional statements correctly.


Go back to the Main Menu

Defining Equations

In Mathematica, an equation is a perfectly valid expression that can be assigned to a variable. An equation is declared by using the logical equals symbol "==":

For instance, the second order differential wave equation can be expressed as such:

Defining variables as equations greatly simplifies specifying the inputs to equation solvers such as Solve or DSolve. See the example here under "Multiple Line Functions".

Go back to the Main Menu


Using Rules

Turning Expressions into Functions

Execution Speed
  1. Use "=" instead of ":=" whenever possible.
  2. Use the decimal value of expressions if the accuracy is not an issue: Using "N[Sqrt[3]]" will execute much faster than simply "Sqrt[3]".
  3. Use a compiled function if needed. Though be careful that if the function calls another function, there may not much of a speed increase even if both functions are compiled. The (ugly) solution is to combine the two functions into a single function and compile just one monolithic function.
  4. Suppress the output of unnecessary graphics, which take up large amouts of memory, especially 3-D graphics. Restart the worksheet and only execute the lines that are necessary by commenting out lines used for testing purposes.
  5. To time an expression, use "Timing[expr]" where expr is the entire expression to be evaluated, including any assignments.

Submit your own!

Please submit your favorite tips and traps!

E-mail a tip, trap or suggestion.

Go Back to the Main Menu