So far, data in these notes has either been typed directly into a script or generated by MATLAB itself. Often, though, data comes from an external file - a log from a sensor, a CSV of test results, a data sheet from a vendor - and results need to be saved back out to a file when a script finishes. This page covers the basics of reading and writing files in MATLAB.

The MATLAB Help Center has a guide on Read and Write to Text Files.

Opening and Closing Files

Before reading or writing a file, MATLAB needs to open it with fopen, which returns a file identifier (fid) used by every other file function:

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

The second argument is the mode: 'r' for reading, 'w' for writing (overwriting anything already in the file), and 'a' for appending to the end of an existing file. When you’re done, always close the file with fclose(fid) to make sure everything you wrote is actually saved to disk.

Writing to a File

fprintf works the same way it does when printing to the Command Window, except with a file identifier as its first argument:

fid = fopen('results.txt', 'w');
fprintf(fid, 'Trial %d: %.2f m/s\n', 1, 245.6);
fprintf(fid, 'Trial %d: %.2f m/s\n', 2, 251.3);
fclose(fid);

This creates results.txt containing one line per trial, with the trial number and speed formatted into each line.

Reading from a File

fgetl reads a single line from an open file as text, returning -1 once there are no more lines left. Combined with a while loop, this reads a file one line at a time until it’s exhausted:

fid = fopen('results.txt', 'r');
while ~feof(fid)
    line = fgetl(fid);
    disp(line)
end
fclose(fid);

feof(fid) returns true once the end of file has been reached, which is exactly the condition a while loop needs: keep reading lines for as long as there are lines left to read, without knowing ahead of time how many that will be.

Higher-Level Functions for Tabular Data

Reading and writing line-by-line is flexible, but for data organized in rows and columns - like a CSV file - MATLAB’s higher-level functions are usually easier:

Function Purpose
readmatrix Read numeric data from a file into a matrix
writematrix Write a matrix to a file
readtable Read a file into a table, keeping column headers and mixed data types
writetable Write a table to a file

For example, data = readmatrix('results.csv') reads an entire CSV file into a matrix in one line, without needing to fopen, loop, or fclose at all.

The MATLAB Help Center has documentation on readmatrix and readtable.

Reading Questions

  1. What does fopen return, and what is it used for?
  2. What are the three basic file modes, and what does each one do?
  3. Why is it important to call fclose after writing to a file?
  4. What does feof check for, and why does it pair naturally with a while loop?
  5. When would readtable be a better choice than reading a file line by line with fgetl?