Matrix creation in MATLAB - Time & Space Complexity
When we create a matrix in MATLAB, the computer needs to set up space and fill values. We want to know how the time it takes changes as the matrix size grows.
How does the work grow when we make bigger matrices?
Analyze the time complexity of the following code snippet.
n = 1000;
A = zeros(n, n);
for i = 1:n
for j = 1:n
A(i,j) = i + j;
end
end
This code creates an n-by-n matrix and fills each element with the sum of its row and column indices.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Filling each element of the matrix inside nested loops.
- How many times: The inner operation runs n x n times, once for each element.
As the matrix size n grows, the number of operations grows by the square of n because we fill every element in a two-dimensional grid.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 |
| 100 | 10,000 |
| 1000 | 1,000,000 |
Pattern observation: When n increases ten times, the work increases one hundred times.
Time Complexity: O(n^2)
This means the time to create and fill the matrix grows proportionally to the square of its size.
[X] Wrong: "Filling the matrix takes time proportional to n, not n squared."
[OK] Correct: Because the matrix has n rows and n columns, you must fill n x n elements, so the work grows with n squared, not just n.
Understanding how matrix creation time grows helps you explain efficiency in tasks like image processing or data tables, where big matrices are common. It shows you can think about how code scales with input size.
"What if we only filled the diagonal elements of the matrix? How would the time complexity change?"