A1.4 Data import and export
A1.4.1 Importing data
There are two ways to load text data (ASCII format) from a file into the workspace.
One method is to use the Import Wizard that is accessible from the file menu (File
Import Data). When the Import Wizar d starts, it will ask you to select the file that
contains the da ta you wish to import. Next, you will be asked to specify the
delimiting character that separates adjacent data values. Often, the delimiter will
be the space character, although a comma, semicolon, or tab character can also be
used as a delimiter. The data extracted from the file are displayed in rows and
columns in the same window for your verification. The Wizard creates a single
variable named after the filename and stores all of the numerical data in that
variable. It also creates another variable for alphabetical data. If row headers or
column headers are present in the data, the Wizard extracts the headers and creat es a
separate variable for them. In the next window, you are asked to choose which
variables to save. When row (or column) headers are available, MATLAB will ask if
you want to save each row (or column) as a separate variable. In this case, each row
variable is named after its corresponding header.
Import of numerical data from a file can be automated within an m-file using the
load function. Consider the following statement:
load a.dat
This is the command syntax for load. The load function will treat the file a.dat as
a text (ASCII) file and will save the numerical data contained in the file to a single
variable of type double. The variable saved in the workspace is a two-dimensional
array and is named a, after the filename. For the load function to execute without
error, the data stored in the file must be in rectangular form, i.e. the number of
elements in each row must be the same. Also, within each row the row elements
should be separated by one or more spaces. The functional form of the syntax for
load is
b = load(a.dat);
Using the functional form you can specify the name of the variable that will
contain the data extracted from a.dat.
A1.4.2 Exporting data
Data generated within a function or script can be output to the screen or to a file
using the fprintf function. This function outputs the data as a character string.
You can specify how the numerical data should appear in the output using
conversion specifiers. The syntax for this function is
fprintf(fid, format, a, b, ...)
where fid is a file identi fier that specifies which file the data should be written to; fid is
an integer and is obtained from the function fopen, e.g.
fid = fopen(’ myfile.txt’ , ’w’ )
573
Introduction to MATLAB