Why string operations are essential in MATLAB - Performance Analysis
String operations are common in many programs, so it is important to understand how their time cost grows.
We want to know how the work needed changes as the string gets longer.
Analyze the time complexity of the following code snippet.
str = 'hello world';
newStr = '';
for i = 1:length(str)
newStr = [newStr str(i)];
end
This code builds a new string by adding one character at a time from the original string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding one character to the new string inside the loop.
- How many times: Once for each character in the original string (length of str).
Each time we add a character, MATLAB creates a new string by copying the old one and adding the new character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 (1+2+...+10) |
| 100 | About 5050 |
| 1000 | About 500500 |
Pattern observation: The work grows much faster than the string length because each addition copies the whole string built so far.
Time Complexity: O(n^2)
This means the time needed grows roughly like the square of the string length.
[X] Wrong: "Adding characters one by one takes time proportional only to the string length."
[OK] Correct: Each addition copies the whole string so far, making the total time grow much faster than just the length.
Understanding how string operations scale helps you write efficient code and explain your choices clearly in real projects or interviews.
"What if we used a MATLAB function that builds the string all at once instead of adding characters one by one? How would the time complexity change?"