Mathematica Tips and Tricks

Loading Packages to Get Additional Functionality

Mechanics of Loading a Package

The basic mechanism to load a package is the Get command, which takes a single argument defining the file.  Two less than signs ("<<") are a shortcut for the Get command. For example, to load the Normal Distribution package (part of the Statistics functions that are shipped with Mathematica, but not loaded by default) we issue the Get command (in this case in the shorthand form).

<<Statistics`NormalDistribution`

The specific form of this command specifies that we want to load the Mathematica context called "NormalDistribution`" (note the trailing backtick, which marks the symbol as a context).  Mathematica has special rules defining how it finds the files that define a context.  However, for the primary packages that will be of use in this course, if Mathematica has been properly installed, we don't have to worry about the mechanics; Mathematica will find the relevant files.

What Packages Should You Load?

Shadowing --- Why Mathematica Won't Recognize a Command

Here is the symptom.  While you think you've loaded all of the commands you need, when you enter a Mathematica command, the input is echoed back to you:CDF[NormalDistribution[μ,σ],x]
CDF[NormalDistribution[μ,σ],x]
As an immediate check, ask Mathematica what definition it's using for the symbol (or symbols) that were echoed back.
?CDF
Global`CDF
?NormalDistribution
Global`NormalDistribution
In this case, Mathematica says they're defined in the Global context.  That means they were undefined until you tried to use them.  Since they were undefined, when Mathematica saw them, it assumed they were user defined variables, and created them in the Global context.  To fix this, explicitly remove them:
Remove[CDF,NormalDistribution]
?CDF
Information::notfound: Symbol \!\(\"CDF\"\) not found. \!\(\*ButtonBox[\"More…\", ButtonStyle->\"RefGuideLinkText\", ButtonFrame->None, ButtonData:>\"General::notfound\"]\)
Now they really are undefined, in all of the contexts currently active.  So reload the necessary package:
<<Statistics`NormalDistribution`
And now the command you're looking for should be effective.  Note that it is not enough to simply exit and restart the Mathematica kernel --- you must explictly Remove[] the symbol.
CDF[NormalDistribution[μ,σ],x]
1/2 (1+Erf[(x - μ)/(2^(1/2) σ)])

If this is insufficent, restarting Mathematica is the next troubleshooting step.

Importing Data

It's easy if the data is formatted "correctly" (i.e. as a pure list of numbers). The Import command will attempt to read in the data into a table (given the appropriate option). If the data is not so formatted, some manipulation may be required.

This assumes that the data is in Devore's data disk, which is in the D:\ drive.  Devore has formatted the data with column names in the first row, which we want to get rid of.  The Delete command accomplishes this by deleting the first record of data.

In[309]:=

datain = Delete[Import["D:\Manual Install\Datasets\ASCII - Comma\CH12\ex12-01.txt", "CSV"], 1]

Import :: nffil : File not found during Import[D:\\Manual Install\\…ma\\CH12\\ex12-01.txt, CSV] .  More…

Delete :: partw : Part  {1} of $Failed does not exist. More…

Out[309]=

Delete[$Failed, 1]

It also works with tab-separated data; in fact, importing tab separated data appears to be more reliable than comma separated data (see below).

In[310]:=

Delete[Import["D:\Manual Install\Datasets\ASCII - Tab\CH12\ex12-01.txt", "TSV"], 1]

Import :: nffil : File not found during Import[D:\\Manual Install\\…ab\\CH12\\ex12-01.txt, TSV] .  More…

Delete :: partw : Part  {1} of $Failed does not exist. More…

Out[310]=

Delete[$Failed, 1]

It's desirable to specify the format of the file as either "TSV" for tab-separated variable or "CSV" for comma-separated variable; Mathematica will attempt to guess the format if you just tell Mathematica the data is a table --- but it has a relatively high error rate.

A flag that the data was read in incorrectly is that extraction operations return unexpected results.  For example, given the above data, the (1,2)th entry should be 0.84.

In[311]:=

datain[[1, 2]]

Part :: partd : Part specification Delete[$Failed, 1][[1, 2]] is longer than depth of object. More…

Out[311]=

Delete[$Failed, 1][[1, 2]]

If the data is read in incorrectly, you may get an odd answer:

In[312]:=

baddata = Delete[Import["D:\Manual Install\Datasets\ASCII - Comma\CH12\ex12-01.txt", "Table"], 1] ;

Import :: nffil : File not found during Import[D:\\Manual Install\\…ma\\CH12\\ex12-01.txt, …] .  More…

Delete :: partw : Part  {1} of $Failed does not exist. More…

In[313]:=

baddata[[1, 2]]

Part :: partd : Part specification Delete[$Failed, 1][[1, 2]] is longer than depth of object. More…

Out[313]=

Delete[$Failed, 1][[1, 2]]

The other Mathematica command that is useful is ReadList.  This command offers more specific control over the format and content of the data.

Data Manipulation

To extract a column of data from an array (e.g. one read in as paired data), use the Column or ColumnTake functions (both of which are part of the Statistics`DataManipulation` package).

Ordinary operations can be applied directly to lists.  List sums can be computed with the Sum command.  So to take the sum of the x_i^2from the set read in in datain above

In[314]:=

datain

Out[314]=

Delete[$Failed, 1]

In[315]:=

datain[[1, 2]]

Part :: partd : Part specification Delete[$Failed, 1][[1, 2]] is longer than depth of object. More…

Out[315]=

Delete[$Failed, 1][[1, 2]]

In[316]:=

xi = Column[datain, 1]

Out[316]=

Column[Delete[$Failed, 1], 1]

In[317]:=

Sum[xi[[i]], {i, Length[xi]}]

Out[317]=

1 + Delete[$Failed, 1]

These functions are particularly useful in computing regression values not output by the standard package.

Graphics and Displays

Combining Graphics

Graphics in Mathematica are the result of two related operations.  The first operation is the actual construction of the graphic object, which is the domain of functions such as "Plot". The detailed behavior of the function is controlled by a series of options; for example, changing the size of the dots plotted is an option.

By default, the primary operations also cause the second operation to take place, which is the actual display of the graphic.  This is not necessarily true, however.  Setting the option "DisplayFunction ->Identity causes the graphic to be created, but not shown.  So to assemble a graphic from several different parts—for example, from a ListPlot and a Plot, we create the individual graphics with DisplayFunction ->Identity, and then use Show to put them together, setting the Show function's DisplayFunction ->$DisplayFunction", which causes it to display the combine graphic.

Tabular Displays

The use of the "TableForm" of output is a convenient way to assemble a series of data.  The command simply takes a matrix of elements (a list of lists, in Mathematica) and displays it in a table, using whatever display forms are appropriate for the individual elements.  For example, the summary display of model parameters

In[318]:=

a = 5.2 ;

Out[319]//TableForm=

  ^ β  = b1       1 = 6.1562  2 r = 27.04
  ^ β  = b       0    0 = 10.4 p  MUT = 2.28035

was created with "TableForm" as shown.

Data Context

Mathematica uses context to define and separate different definitions of the same symbol. Most work in Mathematica is in the "Global`" context, and even if packages are loaded (thus creating other contexts), Mathematica's default handling of the context is generally transparent.

However, there are some cases where some understanding of how Mathematica handles context allows for an easier time in working with the system.

A specific case of this is the use of "Begin ... End" blocks around the definitions of functions inside the various distribution sections above.  Wrapping them inside (appropriately named) contexts allows us to avoid interfering with previously existing distributions, while accessing the definition if needed.

For example, the PDF of the Normal distribution (as defined above)

In[320]:=

NormalDistributionProperties`f[x, μ, σ]

Out[320]=

0.0469344 ^(-0.00692042 (-28 + x)^2)

Other Notes


- p65: notes on defing display function
use of VectorQ as a test of function arg
- note uses of "/;" and "//" as command terminators.
     "/;" is "Condition"
    "//" is "(function evaluation)"
    "/." is "ReplaceAll"
    "->" is "Rule"

Other Miscellaneous Traps

Non-Numeric Assignment

Some Mathematica installations will sometimes incorrectly process an assignment ("=") statement that is followed by the "//N" display command.  The symptom is that a subsequent calculation using the value will fail with an error message related to a non-numeric value.  The solution is to remove the "//N" display form from the assignment (and if necessary, display the computed value separately).

This error is difficult to reproduce; the affected installation will exhibit the error, while other installations will process the same notebook without error.


Created by Mathematica  (July 20, 2006) Valid XHTML 1.1!