0
0
MATLABdata~10 mins

Writing text files (writetable, fprintf) in MATLAB - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to write a table to a text file using writetable.

MATLAB
T = table([1; 2; 3], {'A'; 'B'; 'C'}, 'VariableNames', {'ID', 'Letter'});
writetable(T, '[1]');
Drag options to blanks, or click blank then click option'
A'output.txt'
Boutput.txt
C'output'
Doutput
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the filename.
Omitting the file extension.
2fill in blank
medium

Complete the code to open a file for writing using fopen.

MATLAB
fid = fopen('data.txt', '[1]');
Drag options to blanks, or click blank then click option'
A'rw'
B'w'
C'a'
D'r'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' which is read-only mode.
Using 'a' which appends instead of overwriting.
3fill in blank
hard

Fix the error in the fprintf statement to write a number and a string to the file.

MATLAB
fid = fopen('log.txt', 'w');
num = 10;
str = 'test';
fprintf(fid, '[1]', num, str);
fclose(fid);
Drag options to blanks, or click blank then click option'
A'%d %d\n'
B'%s %d\n'
C'%f %s\n'
D'%d %s\n'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of %d and %s.
Using %f for integers.
4fill in blank
hard

Fill both blanks to write a table to a CSV file without row names.

MATLAB
T = table([4; 5], {'X'; 'Y'}, 'VariableNames', {'Num', 'Char'});
writetable(T, '[1]', 'WriteRowNames', [2]);
Drag options to blanks, or click blank then click option'
A'data.csv'
Btrue
Cfalse
D'data.txt'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .txt extension instead of .csv.
Setting 'WriteRowNames' to true by mistake.
5fill in blank
hard

Fill all three blanks to write formatted data to a file using fprintf.

MATLAB
fid = fopen('results.txt', 'w');
values = [1.5, 2.5, 3.5];
for i = 1:length(values)
    fprintf(fid, '[1]', values(i));
end
fclose(fid);
Drag options to blanks, or click blank then click option'
AValue: %.1f\n
BValue: %d\n
CValue: %f\n
DValue: %s\n
Attempts:
3 left
💡 Hint
Common Mistakes
Using %d which is for integers.
Using %s which is for strings.