Opening the book…
You have already used fprintf to display formatted output in the Command Window. The same function can also write formatted output to a file. The only difference is that we include the file identifier as the first input. The format is:
fprintf(fid, 'format text', values)
If we leave out fid, MATLAB prints to the screen. If we include fid, MATLAB writes to the file associated with that file identifier.
Writing lines to a text file.
fid = fopen('tryIt.txt', 'w');
if fid == -1
disp('File open was not successful!')
else
for i = 1:3
fprintf(fid, 'The loop variable is %d.\n', i);
end
cid = fclose(fid);
if cid == -1
disp('File close was not successful!')
end
end
Solution
This creates a file named tryIt.txt and writes three lines to it:
The loop variable is 1.
The loop variable is 2.
The loop variable is 3.
The permission string w means write mode. If the file already exists, MATLAB overwrites it.
Appending with fprintf
To add new information to the end of an existing file, open the file using append mode, which uses the permission string a.
Writing lines to an existing text File.
fid = fopen('tryIt.txt', 'a');
if fid ~= -1
fprintf(fid, 'This line was added later.\n');
fclose(fid);
end
Suppose a file named tempF.dat stores time of day in the first column and temperature in degrees Fahrenheit in the second column.
8 55 10 70 12 78 14 76 16 70 18 63 20 55
We want to read the data, convert the temperatures to degrees Celsius, and save the new data to a file named tempC.dat.
The conversion formula is:
C = (F - 32) * 5/9
dataF = load('tempF.dat');
time = dataF(:,1);
tempF = dataF(:,2);
tempC = (tempF - 32) * 5/9;
dataC = [time tempC];
save tempC.dat dataC -ascii
This solution uses load and save because the file contains only numeric data in a rectangular format.
A more formatted version using fprintf could include a heading and rounded output:
fid = fopen('tempC_formatted.txt', 'w');
if fid == -1
disp('File open was not successful')
else
fprintf(fid, 'Time Temp_C\n');
fprintf(fid, '----------------\n');
for k = 1:length(time)
fprintf(fid, '%4d %6.2f\n', time(k), tempC(k));
end
fclose(fid);
end
This version gives us more control over how the file looks.
This page titled 9.8: Writing Formatted Text with fprintf was last modified on Tue, 30 Jun 2026 02:12:03 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.
The book could not be loaded just now.