Save the result in Mathematica

Mathematica notebook is a powerful tool to save all the program and data together. Sometimes it is much better to save the result in a separated file for re-use. For example, there is a script to scan the parameters in a wide range. It may take a lot of time. The result is always a big array. It is usually to use “;” to eliminate the result to show. The result has to be re-calculated when the notebook is opened again. Here is the way to save and read the result in a file to avoid taking a lot of time to calculate it.

Mathematica provide functions to deal with the different file systems.

NotebookDirectory[] return the notebook directory. I prefer to store the data in the notebook direction.
SetDirectory[dir] set the working directory and show it. 
SetDirectory[NotebookDirectory[]] set the working directory to the notebook file directory.  

There are two ways to save the data. The first command is put or “>>” for short. It will put the only content of a variable to a text file.

search={{150.081, 1213.62}, {149.994, 500.009}, {149.994, 500.009}, {149.994,
   500.009}, {150.012, 500.009}, {150.012, 500.009}, {150.012, 
  500.009}, ........, {150.003, 2303.49}, {150.003, 
  2303.5}, {150.003, 2303.5}}

search>>search.m  It will create a text file named "search.m". 
FilePrint["search.m"] // show the content of the file

{{150.081, 1213.62}, {149.994, 500.009}, {149.994, 500.009}, {149.994,
   500.009}, {150.012, 500.009}, {150.012, 500.009}, {150.012, 
  500.009}, ........, {150.003, 2303.49}, {150.003, 
  2303.5}, {150.003, 2303.5}}

A variable name is necessary to accept the data when the data is used again.

new_variable=<<"search.m"

Both the variable name and the content can be stored in the second way.

Save["search.m", search]

The file content is:
search = {{150.0807673539748, 1213.6228668636359}, {149.99411890439958, ......

<<"search.m" for reuse. The variable search will be created if there is not a variable called "search", or it will be re-assigned.  

Leave a Comment