Why reading and writing data is fundamental in MATLAB - Performance Analysis
Reading and writing data are basic tasks in programming that affect how long a program takes to run.
We want to know how the time needed changes when the amount of data grows.
Analyze the time complexity of the following code snippet.
filename = 'data.txt';
fileID = fopen(filename, 'r');
data = fscanf(fileID, '%f');
fclose(fileID);
fileID = fopen('output.txt', 'w');
fprintf(fileID, '%f\n', data);
fclose(fileID);
This code reads numbers from a file and then writes them to another file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading and writing each number one by one.
- How many times: Once for each number in the data file.
As the number of numbers in the file grows, the time to read and write grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads and 10 writes |
| 100 | About 100 reads and 100 writes |
| 1000 | About 1000 reads and 1000 writes |
Pattern observation: The time grows roughly in direct proportion to the number of data items.
Time Complexity: O(n)
This means the time needed grows directly with the number of data items to read and write.
[X] Wrong: "Reading or writing a file always takes the same time no matter how big it is."
[OK] Correct: The program must handle each piece of data, so more data means more time.
Understanding how reading and writing data scales helps you explain program speed clearly and shows you know how data size affects performance.
"What if we read the entire file at once instead of number by number? How would the time complexity change?"