Matrix concatenation in MATLAB - Time & Space Complexity
When we join matrices side by side or one after another, the time it takes depends on their sizes.
We want to know how the work grows as the matrices get bigger.
Analyze the time complexity of the following code snippet.
A = rand(n, m);
B = rand(n, p);
C = [A, B]; % Concatenate matrices horizontally
This code creates two matrices and joins them side by side to form a bigger matrix.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Copying all elements from both matrices into a new matrix.
- How many times: Once for each element in both matrices combined.
As the size of the matrices grows, the work to copy elements grows too.
| Input Size (n x m + n x p) | Approx. Operations |
|---|---|
| 10 x 5 + 10 x 3 | 80 |
| 100 x 50 + 100 x 30 | 8,000 |
| 1000 x 500 + 1000 x 300 | 800,000 |
Pattern observation: The operations grow roughly in direct proportion to the total number of elements being joined.
Time Complexity: O(n*(m + p))
This means the time grows in a straight line with the total number of elements in both matrices combined.
[X] Wrong: "Concatenating matrices is instant and does not depend on their size."
[OK] Correct: Actually, MATLAB must copy every element into a new matrix, so bigger matrices take more time.
Understanding how matrix operations scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we concatenate matrices vertically instead of horizontally? How would the time complexity change?"