0
0
MATLABdata~5 mins

String vs character array in MATLAB - Performance Comparison

Choose your learning style9 modes available
Time Complexity: String vs character array
O(n^2)
Understanding Time Complexity

We want to understand how working with strings and character arrays affects the time it takes to run code in MATLAB.

How does the choice between string and character array change the speed of common operations?

Scenario Under Consideration

Analyze the time complexity of concatenating characters to build a text.


str = "";
for k = 1:n
    str = str + "a";
end

charArr = '';
for k = 1:n
    charArr = [charArr 'a'];
end
    

This code builds a string and a character array by adding one character at a time in a loop.

Identify Repeating Operations

Both loops run from 1 to n, repeating the concatenation operation.

  • Primary operation: Adding one character to the existing text each time.
  • How many times: Exactly n times for both string and character array.
How Execution Grows With Input

Each time we add a character, MATLAB creates a new text by copying the old one and adding the new character.

Input Size (n)Approx. Operations
10About 55 copies (1+2+...+10)
100About 5050 copies
1000About 500,500 copies

Pattern observation: The total work grows roughly like the square of n because each addition copies all previous characters.

Final Time Complexity

Time Complexity: O(n^2)

This means the time to build the text grows much faster than the number of characters added, because each step copies all existing characters.

Common Mistake

[X] Wrong: "Adding one character in a loop always takes the same small time, so total time is O(n)."

[OK] Correct: Each addition copies the entire existing text, so the time grows with the length of the text, making the total time much larger.

Interview Connect

Understanding how string building works helps you write faster code and shows you know how data structures affect performance.

Self-Check

"What if we used a pre-allocated character array and filled it instead of concatenating? How would the time complexity change?"