PDF letter size
PDF legal size

How to make a package in Mathematica

Nasser M. Abbasi

July 16, 2010   Compiled on May 22, 2020 at 1:30am

This note describes making a simple package in Mathematica. An example package that contains one function is made showing how to save it and load it into Mathematica and to update it again by adding a second function to it.

Each time a new function is added to the package, the package has to be reloaded.

This note is not meant by any means to be comprehensive, but only to give someone who is new at using Mathematica the minimal set of commands to make a basic package.

More details about packages are found in Mathematica help pages.

  1. Open a new notebook, and write in it the following code in one cell.
  2. Select the cell and change the cell to become an initialization cell as follows:
    Cell->Cell Properties->Initialization Cell.
  3. Now save the notebook. Select Save As. Assuming it is saved as

    A pop-up menu will now ask you about an AUTO SAVE choice, this will happen just before the save is completed, there will be two choices, select the LEFT option by clicking on it.

    Figure 1:Menu

    Now that package is saved. You can close the file foo.nb

  4. To use the function f[x] defined in the package, load the package as follows (this is one easy way to load the package, there are other ways).

    Notice the name used above, it is foo.m and not foo.nb, and notice that the path has two slashes in it. This command can also be written as Get["c:/mydata/foo.m"] even on windows.

    Now, the package is loaded and you can call the function defined inside the package as follows f[2]. The function can also be called by explicitly pre-appending the package name to the function as follows foo`f[2].

  5. To add a second function, say g[x] to the package, open foo.nb again, and change it to look as follows:

    Now save the file foo.nb. Notice that now Mathematica will not ask again about the Auto Save option. This question is only asked the first time.

  6. Close foo.nb. To use the new function added to the package, the package needs to be reloaded again
  7. To see which functions in your package type ?foo`*. That is all. To add more functions, repeat the above 3 steps.

I’d like to thank Bill Rowe and Istvan Zachar on the Math newsgroup for helpful suggestions while working on this note.