CSV file handling in MATLAB - Time & Space Complexity
When working with CSV files in MATLAB, it's important to know how the time to read or write data changes as the file size grows.
We want to understand how the program's running time grows when handling bigger CSV files.
Analyze the time complexity of the following code snippet.
filename = 'data.csv';
data = readmatrix(filename);
for i = 1:size(data, 1)
disp(data(i, :));
end
This code reads a CSV file into a matrix and then prints each row one by one.
- Primary operation: Looping through each row of the data matrix to display it.
- How many times: Once for every row in the CSV file (n times, where n is number of rows).
As the number of rows in the CSV file increases, the number of times the loop runs also increases directly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times loop runs |
| 100 | About 100 times loop runs |
| 1000 | About 1000 times loop runs |
Pattern observation: The work grows in a straight line with the number of rows.
Time Complexity: O(n)
This means the time to process the CSV file grows directly in proportion to the number of rows.
[X] Wrong: "Reading a CSV file always takes the same time no matter how big it is."
[OK] Correct: The bigger the file, the more rows there are to read and process, so it takes longer.
Understanding how file size affects processing time helps you write efficient code and explain your reasoning clearly in real projects or interviews.
"What if we used readtable instead of readmatrix? How would the time complexity change?"