Writing text files (writetable, fprintf) in MATLAB - Time & Space Complexity
When writing data to text files in MATLAB, it's important to know how the time needed grows as the data size grows.
We want to understand how the time to save data changes when we have more rows or more data to write.
Analyze the time complexity of the following code snippet.
% Write table data to a text file
T = table((1:1000)', rand(1000,1), 'VariableNames', {'ID', 'Value'});
writetable(T, 'output.txt');
% Write formatted data line by line
fid = fopen('output2.txt', 'w');
for i = 1:height(T)
fprintf(fid, '%d %.4f\n', T.ID(i), T.Value(i));
end
fclose(fid);
This code writes a table of 1000 rows to text files using two methods: writetable and fprintf in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each row of data to the file.
- How many times: Once for each row in the table (1000 times in this example).
As the number of rows increases, the time to write grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 write operations |
| 100 | 100 write operations |
| 1000 | 1000 write operations |
Pattern observation: Doubling the number of rows roughly doubles the time to write.
Time Complexity: O(n)
This means the time to write grows linearly with the number of rows in the data.
[X] Wrong: "Writing a few extra columns or formatting details does not affect time much."
[OK] Correct: Each extra column means more data to write per row, so the time per row increases, making the total time grow more than expected.
Understanding how file writing time grows helps you explain performance in real projects where saving large data is common.
"What if we changed the loop with fprintf to write multiple rows at once? How would the time complexity change?"