0
0
MATLABdata~5 mins

Matrix concatenation in MATLAB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Matrix concatenation
O(n*(m + p))
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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 380
100 x 50 + 100 x 308,000
1000 x 500 + 1000 x 300800,000

Pattern observation: The operations grow roughly in direct proportion to the total number of elements being joined.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how matrix operations scale helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

"What if we concatenate matrices vertically instead of horizontally? How would the time complexity change?"