File Input and Output in Matlab

In Matlab, you can read many files using the textread command. Additionally we can read a file using the fopen and fscanf commands similar to C file IO. To write data, we use the fprintf function that we are used to.

Textread in Matlab

First you should be familiar with the builtin function textread, as it is the simplest form of file input available in Matlab.


File Opening, Writing to a File, Reading from a File

Here is a sample of how to read a file line by line using the basic file IO commands in Matlab

           
          %
          % Matlab code to read a bunch of integers from a file...
          % using fopen and fscanf.  See the Matlab topic of textread
          % to see how to accomplish this much more easily
          %

          in_file = fopen('name_of_file', 'r'); // read only

          if (in_file == -1)
            error('oops, file can''t be read');
          end

          [number, count] = fscanf(file, '%d', 1);

          while (count == 1) % while we have read a number

            fprintf('We just read %d\n', number);

            [number, count] = fscanf(file, '%d', 1); % attempt to read the next number
          end
        
      

The fscanf Function

fscanf reads formatted data from a file and returns it as an array of values. The syntax is:

        
          [value, number_of_values_read] = fscanf(file_variable,        'format', count);
        
      

The returned information is the value (or values you were after) and the number of values actually read. If the number_of_values_read does not equal the number you wanted (i.e., count) then you must have come to the end of the file.

The format characters are the same as for fprintf, including:



Back to Topics List