Matrix creation in R Programming - Time & Space Complexity
When we create a matrix in R, we want to know how the time to build it changes as the matrix gets bigger.
We ask: How does the work grow when the number of rows and columns increase?
Analyze the time complexity of the following code snippet.
# Create a matrix with n rows and m columns
n <- 100
m <- 50
mat <- matrix(0, nrow = n, ncol = m)
This code creates a matrix filled with zeros having n rows and m columns.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Filling each cell of the matrix with zero.
- How many times: Once for every element, so n times m.
As the number of rows and columns grow, the total work grows by multiplying these two numbers.
| Input Size (n x m) | Approx. Operations |
|---|---|
| 10 x 10 | 100 |
| 100 x 50 | 5,000 |
| 1000 x 1000 | 1,000,000 |
Pattern observation: Doubling rows or columns roughly doubles the work, so total work grows with the product of rows and columns.
Time Complexity: O(n * m)
This means the time to create the matrix grows proportionally to the total number of elements.
[X] Wrong: "Creating a matrix takes the same time no matter its size."
[OK] Correct: The computer must fill every cell, so bigger matrices take more time.
Understanding how matrix creation time grows helps you reason about data size and performance in real tasks.
"What if we create a matrix by filling it row by row in a loop instead of using the matrix() function? How would the time complexity change?"