Bird
Raised Fist0
MATLABdata~5 mins

Writing text files (writetable, fprintf) in MATLAB

Choose your learning style10 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.

Practice

(1/5)
1. Which MATLAB function is best suited to save a table as a CSV file quickly?
easy
A. writetable
B. fprintf
C. fopen
D. load

Solution

  1. Step 1: Understand the purpose of writetable

    writetable is designed to save MATLAB tables directly to files like CSV with minimal code.
  2. Step 2: Compare with other functions

    fprintf is for custom text formatting, fopen opens files but doesn't save tables, and load is for loading data, not saving.
  3. Final Answer:

    writetable -> Option A
  4. Quick Check:

    Save table fast = writetable [OK]
Hint: Use writetable to save tables directly as CSV files [OK]
Common Mistakes:
  • Confusing fprintf with writetable for saving tables
  • Using fopen alone to save data
  • Thinking load saves files
2. Which of the following is the correct syntax to open a file named 'data.txt' for writing in MATLAB?
easy
A. fid = fopen('data.txt', 'w');
B. fid = fopen('data.txt', 'r');
C. fid = fopen('data.txt', 'a');
D. fid = fopen('data.txt', 'x');

Solution

  1. Step 1: Understand fopen modes

    'r' is read-only, 'w' is write (creates or overwrites), 'a' appends, 'x' creates new file but errors if exists.
  2. Step 2: Choose mode for writing

    To write fresh data, use 'w' mode to open file for writing.
  3. Final Answer:

    fid = fopen('data.txt', 'w'); -> Option A
  4. Quick Check:

    Open file for writing = 'w' mode [OK]
Hint: 'w' mode in fopen opens file for writing (overwrite) [OK]
Common Mistakes:
  • Using 'r' mode which is read-only
  • Using 'a' when overwrite is needed
  • Confusing 'x' mode with 'w'
3. What will be the output file content after running this MATLAB code?
fid = fopen('output.txt', 'w');
fprintf(fid, 'Value: %d\n', 42);
fclose(fid);
medium
A. 42
B. Value: 42
C. Value: %d
D. Error: File not closed

Solution

  1. Step 1: Analyze fprintf formatting

    fprintf writes formatted text. '%d' is replaced by integer 42, '\n' adds a newline.
  2. Step 2: Check file closing

    fclose(fid) properly closes the file, so no error occurs.
  3. Final Answer:

    Value: 42 -> Option B
  4. Quick Check:

    Formatted integer output = Value: 42 [OK]
Hint: fprintf replaces %d with number, remember to fclose [OK]
Common Mistakes:
  • Forgetting to close the file
  • Expecting %d to appear literally
  • Confusing output with just the number
4. Identify the error in this MATLAB code snippet that writes numbers to a file:
fid = fopen('numbers.txt', 'w');
fprintf(fid, '%d\n', 1:5);
% Missing fclose(fid)
medium
A. Missing file open mode
B. Using range 1:5 is invalid
C. Incorrect format specifier in fprintf
D. Missing fclose to close the file

Solution

  1. Step 1: Check file opening

    fopen uses 'w' mode correctly, so file opens for writing.
  2. Step 2: Check file closing

    The code does not call fclose(fid), which is necessary to save and release the file.
  3. Final Answer:

    Missing fclose to close the file -> Option D
  4. Quick Check:

    Always fclose after writing [OK]
Hint: Always fclose after writing to save file properly [OK]
Common Mistakes:
  • Forgetting fclose causes incomplete writes
  • Thinking fprintf needs different format for vectors
  • Assuming fopen mode is missing
5. You want to save a table T with columns 'Name' and 'Score' to a CSV file, but only include rows where Score > 50. Which MATLAB code correctly does this?
hard
A. fid = fopen('filtered.csv', 'w'); fprintf(fid, '%s, %d\n', T.Name, T.Score); fclose(fid);
B. fprintf('filtered.csv', '%s, %d\n', T.Name, T.Score);
C. writetable(T(T.Score > 50, :), 'filtered.csv');
D. writetable(T, 'filtered.csv');

Solution

  1. Step 1: Filter rows where Score > 50

    Use logical indexing: T.Score > 50 selects rows with Score greater than 50.
  2. Step 2: Use writetable to save filtered table

    Pass filtered rows T(T.Score > 50, :) to writetable to save only those rows.
  3. Final Answer:

    writetable(T(T.Score > 50, :), 'filtered.csv'); -> Option C
  4. Quick Check:

    Filter rows then writetable = writetable(T(T.Score > 50, :), 'filtered.csv'); [OK]
Hint: Filter table rows before writetable to save subset [OK]
Common Mistakes:
  • Using fprintf without opening file
  • Not filtering rows before saving
  • Saving entire table without filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard