The writetable function saves a table variable to a text file, such as a CSV or TXT file, making it easy to export structured data.
Click to reveal answer
beginner
How do you use fprintf to write formatted text to a file in MATLAB?
You first open a file with fopen, then use fprintf with a file identifier and a format string to write text, and finally close the file with fclose.
Click to reveal answer
beginner
What is the purpose of the format specifier in fprintf?
The format specifier tells MATLAB how to display the data (like %d for integers, %f for floating-point numbers, %s for strings), controlling the output style.
Click to reveal answer
beginner
Why should you always use fclose after writing to a file?
Closing the file with fclose ensures all data is saved properly and frees system resources, preventing file corruption or access issues.
Click to reveal answer
intermediate
Can writetable write files other than CSV? Give an example.
Yes, writetable can write text files like tab-delimited TXT files by specifying the delimiter option, e.g., writetable(T, 'file.txt', 'Delimiter', '\t').
Click to reveal answer
Which MATLAB function is best for writing a table directly to a CSV file?
Awritetable
Bfprintf
Cfopen
Dload
✗ Incorrect
writetable is designed to save tables directly to files like CSV.
What must you do before using fprintf to write to a file?
AUse <code>load</code> first
BClose the file with <code>fclose</code>
CConvert data to string
DOpen the file with <code>fopen</code>
✗ Incorrect
You must open the file with fopen to get a file ID for fprintf.
What does the format specifier %f mean in fprintf?
AFloating-point number
BInteger
CString
DCharacter
✗ Incorrect
%f formats numbers as floating-point values.
What happens if you forget to call fclose after writing a file?
ANothing happens
BFile deletes automatically
CData might not be saved properly
DMATLAB crashes
✗ Incorrect
Not closing the file can cause data loss or file corruption.
Which option allows writetable to write tab-delimited files?
fopen uses 'w' mode correctly, so file opens for writing.
Step 2: Check file closing
The code does not call fclose(fid), which is necessary to save and release the file.
Final Answer:
Missing fclose to close the file -> Option D
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?