Mathematica

Mathematica command ``ReadList''

Reading in a simple list of numbers

A file containing a bunch of numbers can be read in as one long list as follows:

	ydata = ReadList["filename", Real];

The resulting vector (``ydata'') will contain all n numbers that the file contained, separated by any combination of blanks, tabs, and newlines. If you only wanted to read in, say, the first 50 values, then the command


	ydata = ReadList["filename", Real, 50];
makes ydata a list (vector) of the first 50 values in the file.

Reading in x and y values

Sometimes a file consists of a bunch of pairs of numbers, typically one x-value and one y-value per line. To read this data in as a list of {x,y} pairs, use

	xydata = ReadList["filename", {Real,Real}];

Again, ReadList reads to the end of the file, getting as many pairs of numbers as it can. To get only the first 25 pairs of x-y data, use


	xydata = ReadList["filename", {Real,Real}, 25];
instead.

This data will be in the form xydata = { {x1,y1}, {x2,y2}, ..., {xn,yn} }. This is useful for many purposes (such as plotting with ListPlot), but sometimes you want to extract just the x-values or just the y-values. To do that, you use the transpose of xydata, which is a 2-element list, Transpose[xydata] = { {x1,x2,...,xn}, {y1,y2,...,yn} }. The list of only the y-values, then, would be Transpose[xydata][[2]].

Reading in an m·n grid of values

A file containing mn numbers, representing the elements of an m-by-n matrix, or the values on an m-by-n grid, should be read in ``gulps'' of n numbers at a time:

	griddata = ReadList["filename", Table[Real,{n}]];
or
	griddata = ReadList["filename", Table[Real,{n}], m];

The first variation just reads groups of n numbers at a time, to the end of the file; the second variation specifies that griddata should take only the first m rows of n numbers each. The result is an m-by-n array of data;

z1 z2 z3 ... zn
zn+1 zn+2 zn+3 ... z2n
z2n+1 z2n+2 z2n+3 ... z3n
. .
. .
. .
z(m-1)n+1 z(m-1)n+2 z(m-1)n+3 ... zmn

So griddata[[1]] is the list of the first n numbers in the file. The vector Transpose[griddata][[3]] is the list of numbers in the 3rd column of the matrix, i.e. { z3, zn+3, ..., z(m-1)n+3 }.



Index