Department of Engineering

IT Services

Matlab - File Input and Formatted Output

Introduction

Matlab has routines to read and write ASCII files. People who've use C's file handling routines should find the methods familiar, though even then there are surprises.

Note that for particular formats there are specialised routines - xmlread and xmlwrite for XML files, and various Spreadsheet/database routines

File opening and closing

  • fid=fopen('foo') in unix prepares for reading text from a file called foo. On PCs you'd need to use fid=fopen('foo','rt').
  • fid=fopen('foo','w') prepares for writing text to a file, creating the file if necessary. On PCs you'd need to use fid=fopen('foo','wt'). fid=fopen('foo','a') appends to the file.
  • fclose closes a file opened by fopen. E.g. fclose(fid). It returns 0 if successful and -1 if not.
For details, see

Output

Output's usually simpler than input because less error handling's needed. save is easier to use, though fprintf offers more control.

  • save can be used to produce ascii files. For example,
        x=magic(3) % create and display a 3x3 array
        save blah.dat x -ascii
    
    produces a file called blah.dat containing this
       8.0000000e+00   1.0000000e+00   6.0000000e+00
       3.0000000e+00   5.0000000e+00   7.0000000e+00
       4.0000000e+00   9.0000000e+00   2.0000000e+00
    
    The format's rather inflexible, which is why you may need to use fprintf
  • fprintf writes formatted data to a text file. You need to open the file first. For example,
      x=magic(3)
      fid=fopen('blah.dat','w');
      fprintf(fid,'%d', x);
      fclose(fid);
    
    produces a file containing
      834159672
    
    where each value is printed out as an integer. Note that fprintf needs to know
    • which file it's printing to (the 1st argument)
    • how values should be displayed (the 2nd argument). This is done using a "format string" - %d means integer. %f mean float. %6.2f means float with up to 6 digits, 2 digits after the decimal point. The string is re-used until output ends.
    • the values to be output (the other arguments). The number of elements in the array needs to be a multiple of the number of items in the format string

    The fprintf command is flexible but not especially intuitive. You'll have to read the online documentation to see all the alternative format strings you can use. Here are a few examples

    • fprintf(fid,'%d ', x); - adds a space after each number
    • fprintf(fid,'%d\n', x);- adds a linebreak after each number
    • fprintf(fid,'%f ', x); - prints each number as a float and adds a space after each number
    • fprintf(fid,'%d %f %f\n', x); - prints the 1st number as an integer, then the 2nd and 3rd as floats (with spaces) then a newline, continuing this pattern until the end of the array is reached, thus producing a file like this
      8 3.000000 4.000000
      1 5.000000 9.000000
      6 7.000000 2.000000
      
    Anything in the format string that's not preceded by a '%' sign is printed "as is", so fprintf(fid,'The number=%d\n', x); is possible.

For details, see

Input

textread tries to read a whole file, which might be ok if all the lines in the file have the same format. fscanf can also read a whole file, though it can read less if you want. fgetl and fgets read a line at a time

  • fgetl reads a line of text from a file, discarding any newline character (fgets keeps the newline character). For example the following code creates a file as above, then reads the first line from it.
      x=magic(3)
      fid=fopen('blah.dat','w');
      fprintf(fid,'%d %d %d\n', x);
      fclose(fid);
    
      fid=fopen('blah.dat');
      s=fgetl(fid);
    
    The resulting string s will contain
      8 3 4
    
    You can extract the numbers from this string using sscanf; e.g. y=sscanf(s,'%d') will put the numbers into an array called y.
  • fscanf can be used to extract the numbers directly from the file, combining the behaviour of fgetl and sscanf. For example,
      x=magic(3)
      fid=fopen('blah.dat','w');
      fprintf(fid,'%d %d %d\n', x);
      fclose(fid);
    
      fid=fopen('blah.dat');
      y=fscanf(fid,'%d');
    
    will read all the numbers in the file, creating an column vector y that can be reshaped if necessary. fscanf is rather like the inverse of fprintf, with a similarly flexible format string that is reused until the end of the file is reached. You can limit how many numbers are read. Replacing the fscanf line above by
      
      while(~feof(fid)) % while not at the end of the file
        [b,numbersread]=fscanf(fid,'%d',3);
        b
      end
    
    will read 3 elements at a time into b, producing an empty b at the 4th attempt.
  • textread reads formatted data from text files. It's useful when all lines of a text file have the same format. For example, if a file called 'children' contains
       Name=Diana Age=10 Height=1.21
       Name=Tom Age=11 Height=1.25
       Name=Les    Age=9 Height=1.01
    
    then
       [names, ages, heights]=textread('children','Name=%s Age=%f Height=%f')
    
    reads the names, ages and heights into the corresponding arrays. This uses a similar format string to fscanf - %s means that a string is expected.

For details and further examples, see

See also Mathworks' File I/O Guide.