Dynamic field names in MATLAB - Time & Space Complexity
We want to see how the time needed to run code with dynamic field names changes as the input grows.
How does using dynamic field names affect the speed when we add more fields?
Analyze the time complexity of the following code snippet.
fields = {'a', 'b', 'c', 'd', 'e'};
S = struct();
for i = 1:length(fields)
fieldName = fields{i};
S.(fieldName) = i * 10;
end
This code creates a structure and adds fields using names stored in a list, one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of field names and adding each as a field to the structure.
- How many times: Once for each field name in the list (n times).
Each new field is added one after another, so the time grows as we add more fields.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 field additions |
| 100 | About 100 field additions |
| 1000 | About 1000 field additions |
Pattern observation: The time needed grows directly with the number of fields added.
Time Complexity: O(n)
This means the time to add fields grows in a straight line as the number of fields increases.
[X] Wrong: "Adding fields with dynamic names is instant no matter how many fields there are."
[OK] Correct: Each new field requires some work, so more fields mean more time.
Understanding how dynamic field names affect speed helps you write clear and efficient code, a skill useful in many coding tasks.
"What if we used a nested loop to add fields inside fields? How would the time complexity change?"