0
0
MATLABdata~5 mins

Writing text files (writetable, fprintf) in MATLAB

Choose your learning style9 modes available
Introduction

We write data to text files to save results or share information with others. It helps keep data outside the program for later use.

Saving a table of data after analysis to share with a colleague.
Exporting results from a program to a readable text file.
Logging messages or results during a program run for review.
Creating a report file with formatted numbers and text.
Backing up data in a simple text format for easy access.
Syntax
MATLAB
writetable(T, filename)
fprintf(fileID, formatSpec, A)

writetable saves tables directly to text files like CSV.

fprintf writes formatted text to a file opened with fopen.

Examples
Saves the table T to a CSV file named 'data.csv'.
MATLAB
writetable(T, 'data.csv')
Opens 'log.txt' for writing, writes a formatted number, then closes the file.
MATLAB
fileID = fopen('log.txt', 'w');
fprintf(fileID, 'Value: %.2f\n', 3.14);
fclose(fileID);
Sample Program

This program creates a simple table, saves it as a CSV file using writetable, then writes the same data to a text file with tabs using fprintf. Finally, it reads and prints both files to show the saved content.

MATLAB
T = table([1; 2; 3], {'A'; 'B'; 'C'}, 'VariableNames', {'ID', 'Label'});
writetable(T, 'output.csv');

fileID = fopen('output.txt', 'w');
fprintf(fileID, 'ID\tLabel\n');
for i = 1:height(T)
    fprintf(fileID, '%d\t%s\n', T.ID(i), T.Label{i});
end
fclose(fileID);

% Read back the files to show content
csvContent = fileread('output.csv');
txtContent = fileread('output.txt');

fprintf('CSV file content:\n%s\n', csvContent);
fprintf('TXT file content:\n%s\n', txtContent);
OutputSuccess
Important Notes

Always close files with fclose after using fopen to avoid errors.

Use \n for new lines and \t for tabs in fprintf format strings.

writetable automatically handles commas and quotes for CSV files.

Summary

writetable is easy for saving tables directly to CSV files.

fprintf gives control to write formatted text line by line.

Always open files before writing and close them after to keep data safe.