Structure arrays in MATLAB - Time & Space Complexity
When working with structure arrays in MATLAB, it is important to understand how the time to access or modify data grows as the array gets bigger.
We want to know how the number of operations changes when we work with more elements in the structure array.
Analyze the time complexity of the following code snippet.
% Create a structure array with n elements
for i = 1:n
students(i).name = sprintf('Student%d', i);
students(i).score = randi(100);
end
% Access all scores and sum them
totalScore = 0;
for i = 1:n
totalScore = totalScore + students(i).score;
end
This code creates a structure array of students with names and scores, then sums all the scores.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the structure array to assign fields and then to access the scores.
- How many times: Each loop runs exactly n times, where n is the number of elements in the structure array.
As the number of students (n) increases, the total number of operations grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 for creation + 10 for summing) |
| 100 | About 200 (100 + 100) |
| 1000 | About 2000 (1000 + 1000) |
Pattern observation: The operations double when the input size doubles, showing a steady, linear growth.
Time Complexity: O(n)
This means the time it takes grows directly in proportion to the number of elements in the structure array.
[X] Wrong: "Accessing fields in a structure array is instant and does not depend on the number of elements."
[OK] Correct: Accessing each element's field requires going through each element, so the time grows with the number of elements.
Understanding how structure arrays scale helps you write efficient MATLAB code and answer questions about data handling in interviews confidently.
"What if we used vectorized operations or built-in functions instead of loops? How would the time complexity change?"