0
0
MATLABdata~5 mins

Writing text files (writetable, fprintf) in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing text files (writetable, fprintf)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the number of rows increases, the time to write grows roughly in direct proportion.

Input Size (n)Approx. Operations
1010 write operations
100100 write operations
10001000 write operations

Pattern observation: Doubling the number of rows roughly doubles the time to write.

Final Time Complexity

Time Complexity: O(n)

This means the time to write grows linearly with the number of rows in the data.

Common Mistake

[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.

Interview Connect

Understanding how file writing time grows helps you explain performance in real projects where saving large data is common.

Self-Check

"What if we changed the loop with fprintf to write multiple rows at once? How would the time complexity change?"