Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

Exporting to Text Data Files

If you want to use your data in another application that reads ASCII files, MATLAB functions offer several data export options. For example, you can create a:

Additional MATLAB functions export data to spreadsheets, scientific data formats, and other file formats. For a complete list of supported formats, see the file formats table.

Writing to Delimited Data Files

To export a numeric array as a delimited ASCII data file, you can use either the save function, specifying the -ASCII qualifier, or the dlmwrite function.

Both save and dlmwrite are easy to use. With dlmwrite, you can specify any character as a delimiter, and you can export subsets of an array by specifying a range of values.

However, save -ascii and dlmwrite do not accept cell arrays as input. To create a delimited ASCII file from the contents of a cell array, do one of the following:

Exporting a Numeric Array to an ASCII File Using save

To export the array A, where

A = [ 1 2 3 4 ; 5 6 7 8 ];

to a space-delimited ASCII data file, use the save function as follows:

save my_data.out A -ASCII

To view the file, use the type function:

type my_data.out

1.0000000e+000  2.0000000e+000  3.0000000e+000  4.0000000e+000
5.0000000e+000  6.0000000e+000  7.0000000e+000  8.0000000e+000

When you use save to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file. For example, if you write the character string 'hello' to a file, save writes the values

104 101 108 108 111

to the file in 8-digit ASCII format.

To write data in 16-digit format, use the -double option. To create a tab-delimited file instead of a space-delimited file, use the -tabs option.

Exporting a Numeric Array to an ASCII File Using dlmwrite

To export a numeric or character array to an ASCII file with a specified delimiter, use the dlmwrite function.

For example, to export the array A,

A = [ 1 2 3 4 ; 5 6 7 8 ];

to an ASCII data file that uses semicolons as a delimiter, use this command:

dlmwrite('my_data.out',A, ';')

To view the file, use the type function:

type my_data.out

1;2;3;4
5;6;7;8

By default, dlmwrite uses a comma as a delimiter. You can specify a space (' ') or other character as a delimiter. To specify no delimiter, use empty quotation marks ('').

Exporting a Cell Array to a Text File

To export a cell array that contains nonnumeric data to a text file, use the fprintf function.

The fprintf function is flexible, but requires that you provide details about the format of your data. Describe each field using format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a number in fixed-point notation. (For a complete list of format specifiers, see the fprintf reference page.)

The character that you use to separate the format specifiers determines the delimiter for the output file. For example, a format string such as '%d,%d,%d' creates a comma-separated file, while the format '%d %d %d' creates a space-delimited file.

Preface any calls to fprintf with a call to fopen to open the file, and, when finished, close the file with fclose. By default, fopen opens a file for read-only access. Use the permission string 'w' to write to the file.

For example, consider the array mycell, where

mycell = { 'a' 1 2 3 ; 'b' 4 5 6 };

To export the cell array, print one row of data at a time. Include a newline character at the end of each row ('\n').

Send fprintf the file identifier and the format specifiers to describe the fields in each row:

[nrows,ncols]= size(mycell);

filename = 'celldata.dat';
fid = fopen(filename, 'w');

for row=1:nrows
    fprintf(fid, '%s %d %d %d\n', mycell{row,:});
end

fclose(fid);

To view the file, use the type function:

type celldata.dat

a 1 2 3
b 4 5 6

For more information, see Writing to Text Data Files with Low-Level I/O.

Writing to a Diary File

To keep an activity log of your MATLAB session, use the diary function. diary creates a verbatim copy of your MATLAB session in a disk file (excluding graphics).

For example, if you have the array A in your workspace,

A = [ 1 2 3 4; 5 6 7 8 ];

execute these commands at the MATLAB prompt to export this array using diary:

  1. Turn on the diary function. Optionally, you can name the output file diary creates:

    diary my_data.out
    
  2. Display the contents of the array you want to export. This example displays the array A. You could also display a cell array or other MATLAB class:

    A =
        1     2     3     4
        5     6     7     8
    
  3. Turn off the diary function:

    diary off
    

    diary creates the file my_data.out and records all the commands executed in the MATLAB session until you turn it off:

    A =
    
         1     2     3     4
         5     6     7     8
    
    diary off
    
  4. Open the diary file my_data.out in a text editor and remove the extraneous text, if desired.

Writing to Text Data Files with Low-Level I/O

To create rectangular, delimited ASCII files (such as CSV files) from numeric arrays, use high-level functions such as dlmwrite. For more information, see Writing to Delimited Data Files.

To create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes, use the low-level fprintf function. For more information, see the following sections:

Opening the File

As with any of the low-level I/O functions, before exporting, open or create a file with fopen, and obtain a file identifier. By default, fopen opens a file for read-only access, so you must specify the permission to write or append, such as 'w' or 'a'.

When you finish processing the file, close it with fclose(fid).

Describing the Output

fprintf accepts arrays as inputs, and converts the numbers or characters in the arrays to text according to your specifications.

For example, to print floating-point numbers, specify '%f'. Other common conversion specifiers include '%d' for integers or '%s' for strings. For a complete list of conversion specifiers, see the fprintf reference page.

To move to a new line in the file, use '\n'.

fprintf reapplies the conversion information to cycle through all values of the input arrays in column order.

For example, create a file named exptable.txt that contains a short table of the exponential function, and a text header:

% create a matrix y, with two rows
x = 0:0.1:1;
y = [x; exp(x)];

% open a file for writing
fid = fopen('exptable.txt', 'w');

% print a title, followed by a blank line
fprintf(fid, 'Exponential Function\n\n');

% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f  %f\n', y);
fclose(fid);

To view the file, use the type function:

type exptable.txt

This returns the contents of the file:

Exponential Function

0.000000  1.000000
0.100000  1.105171
0.200000  1.221403
0.300000  1.349859
0.400000  1.491825
0.500000  1.648721
0.600000  1.822119
0.700000  2.013753
0.800000  2.225541
0.900000  2.459603
1.000000  2.718282

Additional Formatting Options.   Optionally, include additional information in the call to fprintf to describe field width, precision, or the order of the output values. For example, specify the field width and number of digits to the right of the decimal point in the exponential table:

fid = fopen('exptable_new.txt', 'w');

fprintf(fid, 'Exponential Function\n\n');
fprintf(fid, '%6.2f  %12.8f\n', y);

fclose(fid);

exptable_new.txt contains the following:

Exponential Function

  0.00    1.00000000
  0.10    1.10517092
  0.20    1.22140276
  0.30    1.34985881
  0.40    1.49182470
  0.50    1.64872127
  0.60    1.82211880
  0.70    2.01375271
  0.80    2.22554093
  0.90    2.45960311
  1.00    2.71828183

For more information, see Formatting Strings in the Programming Fundamentals documentation, and the fprintf reference page.

Appending or Overwriting Existing Files

By default, fopen opens files with read access. To change the type of file access, use the permission string in the call to fopen. Possible permission strings include:

To open a file for both reading and writing or appending, attach a plus sign to the permission, such as 'w+' or 'a+'. For a complete list of permission values, see the fopen reference page.

Example — Appending to an Existing Text File.   Create a file changing.txt as follows:

myformat = '%5d %5d %5d %5d\n';

fid = fopen('changing.txt','w');
fprintf(fid, myformat, magic(4));
fclose(fid);

The current contents of changing.txt are:

   16     5     9     4
    2    11     7    14
    3    10     6    15
   13     8    12     1

Add the values [55 55 55 55] to the end of file:

% open the file with permission to append
fid = fopen('changing.txt','a');

% write values at end of file
fprintf(fid, myformat, [55 55 55 55]);

% close the file 
fclose(fid);

To view the file, use the type function:

type changing.txt

This command returns the new contents of the file:

   16     5     9     4
    2    11     7    14
    3    10     6    15
   13     8    12     1
   55    55    55    55

Example — Overwriting an Existing Text File.   Replace the third line of the file changing.txt from the previous example with [33 33 33 33]:

replaceLine = 3;
myformat = '%5d %5d %5d %5d\n';

% Open the file with permission to read and update.
% Use fgetl, which reads a line at a time,
% to place the file position indicator at the third line.

fid = fopen('changing.txt','r+');
for k=1:(replaceLine-1);
    fgetl(fid);
end;

% call fseek between read and write operations
fseek(fid, 0, 'cof');

% print the new values
fprintf(fid, myformat, [33 33 33 33]);

% close the file
fclose(fid);

To view the file, use the type function:

type changing.txt

This command returns the new contents of the file:

   16     5     9     4
    2    11     7    14
   33    33    33    33
   13     8    12     1
   55    55    55    55

Opening Files with Different Character Encodings

Encoding schemes support the characters required for particular alphabets, such as those for Japanese or European languages. Common encoding schemes include US-ASCII or UTF-8.

If you do not specify an encoding scheme, fopen opens files for processing using the default encoding for your system. To determine the default, open a file, and call fopen again with the syntax:

[filename, permission, machineformat, encoding] = fopen(fid);

If you specify an encoding scheme when you open a file, the following functions apply that scheme: fscanf, fprintf, fgetl, fgets, fread, and fwrite.

For a complete list of supported encoding schemes, and the syntax for specifying the encoding, see the fopen reference page.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS