IMSE Chapter 11

IMSE-11(I-O).nb
Importing and Exporting Data in Mathematica
RCH 7/23/01
revised 6/11/02 - rjerwin

This notebook shows you how to import and export data to and from a Mathematica notebook.  Such situations occur fairly frequently.  For example, you may have acquired data from an experiment and want to use Mathematica to analyze it.  In other cases, you may generate results with Mathematica and then want to use a fancier graphics program to produce graphs and slides for a paper or a talk.  (Mathematica does have nice graphics capabilities, but some of the graphics editing is a bit awkward.)

In the first example, we generate some data in Mathematica by using a Do loop to create an array of numbers and their squares.  The numbers range from 1 to 20.  (Do loops and other progamming features are introduced in IMSE-09.)

Do[a[k, 1] = k; a[k, 2] = k^2, {k, 1, 20}]

Mathematica will export data (in this case, a set of numbers) only if it is in the form of a list.  The commands below produce a list that has two columns and 20 rows.  Each row consists of a number in the first column and the square of that number in the second column.  The last command puts the list in table format.

(*Need to convert the array into a list.*) 
dataList  =  Array[a, {20, 2}];  (*two columns,  
      20 rows*) 
dataList  // TableForm

In the final step, we send the data dataList to a file located on the C:\ drive.  If you want to send the file to a different directory, simply add more detail to the filename string.  For example, "C:\My Documents\Math\dataTest.dat".  The last part of the Export[] command ("Table") tells Mathematica to put the data into a Table format, which makes it easy for spreadsheet programs and graphics programs to import the data. 

If you activate the following cell, Mathematica will respond with the path and file name if the data have been successfully saved.

Export["C:\dataTest.dat", dataList, "Table"]

Let's now reverse our procedure and bring some data into Mathematica.  The following cell has a command that brings the data we just stored back into Mathematica in a Table format, much as they would look in a spreadsheet.  If you want to suppress the printing of the imported data, simply put a semicolon at the end of the command.

mydata = Import ["C:\dataTest.dat", "Table"]

NOTE: When using Import[], you can find the file path name (such as "C:\My Documents\Math\dataTest.dat") very easily by going to "Input" on the menu bar and then to "Get File Path..."

Working with the Imported Data

If your data consists of just a single column of numbers, you can treat it as a list in the usual way.  In the case of mydata, we have a more complicated list to deal with.  Suppose we want to separate the numbers from their squares.  We can do this by generating two new lists that pull out the relevant parts.  The first command pulls out all the numbers in the first column.  The second command extracts the squares of the numbers from the  second column of myData.

mynumber = mydata[[All, 1]]
mynumbersquared = mydata[[All, 2]]

Here is an example of my own work.  Data from an experiment looking at laser signals as a function of magnetic field resulted in ASCII data stored in file.  Each row of data contained the magnetic field value in column 1, and various signals in columns 2-5.  For the analysis, I needed just the magnetic field values and the signal from column 5.  After reading in the list laserdata with commands like those given above, I used the following two statements to extract the magnetic field values and to put them in a list named bField.  The signal values in column 5 were extracted and assigned to the list cpAsym.  Those lists could then be used for further calculations in the data analysis.  Note the double square brackets used with the list laserdata to access the row and column labels.  NOTE:  Nothing will happen if you try to activate these commands since we haven't defined a list laserdata.

bField = 
        laserdata[[All, 1]];
cpAsym = laserdata[[All, 5]];

In the next set of commands the magnetic field values and the cpAsym values are brought together into a single list called datList in order to use ListPlot[] to plot the data points (bField, cpAsym).  (ListPlot assumes that the x (abcissa) value is in the first column and the y (ordinate) value is in the second column.)   Recall that the command Length[listname] finds the number of entries in the list.

kmax = 
        Length[bField];
Do[datList[k, 1] = bField[[k]]; 
      datList[k, 2] = cpAsym[[k]], {k, 1, 
        kmax}]  
plotList = Array[datList, {kmax, 2}]
ListPlot[plotList];

Exercise:  In the following cell, use ListPlot[] and mydata to plot the squares of the numbers (ordinate) as a function of the numbers (abcissa).  Also try recombining the lists mynumber and myumbersquared to generate a new list.  Then plot it.

Exporting Mathematica Graphs

In many situations you may want to export a Mathematica graph to another program as you write a lab report or prepare a presentation.  There are several ways to do this.  The easiest is to select the graph by moving the cursor on top of the graph and left-clicking.  A dotted line frame with black boxes on the corners and sides should appear.  This tells you that the graph has been selected.  Try this with the graph you just made.

To export the graph,  either hit CTRL+c or select "Edit"->"Copy" on the menu bar.  Either procedure places the graph on the Windows Clipboard.  Then go to the destination program with your destination document open and use "Edit"->"Paste Special" to paste the graph into the document.  NOTE:  You can use "Edit"->"Paste" just as well except that WORD and POWERPOINT then give you less flexibility in positioning the graph within the document.  But in many cases that is not a major issue.  When you use "Paste Special," you have a choice of several formats.  The Picture format gives you the most flexibility, though I have found that the pasted graph is initially extremely small.

The other way to export Mathematica graphs is to save them in a file.  You can choose a variety of file formats (TIFF, GIF, etc.).  To save the graph to a file, select the graph by left-clicking on it.  Then use "Edit"->"Save Selection As" and choose the desired format.  Mathematica Help gives you more details under "Export."