0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use fprintf for File Output in MATLAB

In MATLAB, use fprintf with a file identifier obtained from fopen to write formatted text to a file. First, open the file with fid = fopen(filename, 'w'), then write using fprintf(fid, formatSpec, data), and finally close the file with fclose(fid).
๐Ÿ“

Syntax

The basic syntax to write formatted text to a file in MATLAB is:

  • fid = fopen(filename, permission): Opens the file and returns a file identifier fid.
  • fprintf(fid, formatSpec, A, ...): Writes data to the file using the specified format.
  • fclose(fid): Closes the file to save changes and free resources.

Explanation: filename is the name of the file as a string, permission is usually 'w' for writing (creates or overwrites), and formatSpec defines how data is formatted (like '%d' for integers or '%f' for floats).

matlab
fid = fopen('myfile.txt', 'w');
fprintf(fid, 'Hello, %s!\n', 'world');
fclose(fid);
๐Ÿ’ป

Example

This example opens a file named data.txt, writes formatted numbers and text, then closes the file. It shows how to write multiple lines with different data types.

matlab
filename = 'data.txt';
fid = fopen(filename, 'w');
if fid == -1
    error('Cannot open file for writing');
end

% Write a header line
fprintf(fid, 'ID\tName\tScore\n');

% Write data lines
fprintf(fid, '%d\t%s\t%.2f\n', 1, 'Alice', 95.5);
fprintf(fid, '%d\t%s\t%.2f\n', 2, 'Bob', 88.0);

fclose(fid);

% Display file content
fileContent = fileread(filename);
disp(fileContent);
Output
ID Name Score 1 Alice 95.50 2 Bob 88.00
โš ๏ธ

Common Pitfalls

  • Not checking if fopen succeeded: Always verify fid is not -1 before writing.
  • Forgetting to close the file: Use fclose(fid) to save and release the file.
  • Incorrect format specifiers: Mismatched formatSpec and data types cause errors or wrong output.
  • Writing without file identifier: Using fprintf without fid writes to the command window, not the file.
matlab
%% Wrong way: Not checking fopen
fid = fopen('file.txt', 'w');
fprintf(fid, '%d\n', 123);
% If fopen fails, fid = -1, this causes error

%% Right way: Check fopen
fid = fopen('file.txt', 'w');
if fid == -1
    error('File open failed');
end
fprintf(fid, '%d\n', 123);
fclose(fid);
๐Ÿ“Š

Quick Reference

fprintf file writing cheat sheet:

FunctionDescription
fopen(filename, 'w')Open file for writing (overwrite)
fprintf(fid, formatSpec, data)Write formatted data to file
fclose(fid)Close the file
%dInteger format specifier
%fFloating-point format specifier
%sString format specifier
\nNew line character
FunctionDescription
fopen(filename, 'w')Open file for writing (overwrite)
fprintf(fid, formatSpec, data)Write formatted data to file
fclose(fid)Close the file
%dInteger format specifier
%fFloating-point format specifier
%sString format specifier
\nNew line character
โœ…

Key Takeaways

Always open files with fopen and check the file identifier before writing.
Use fprintf with the file identifier to write formatted text to files.
Close files with fclose to save data and free resources.
Match format specifiers in fprintf to the data types you write.
Forgetting to close files or check fopen results causes errors or data loss.