Reshaping arrays in MATLAB - Time & Space Complexity
When we reshape arrays in MATLAB, we change their shape without changing the data.
We want to know how the time to reshape grows as the array size grows.
Analyze the time complexity of the following code snippet.
A = 1:1000; % Create a row vector with 1000 elements
B = reshape(A, 100, 10); % Reshape into a 100x10 matrix
This code reshapes a 1D array into a 2D matrix by rearranging elements.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Updating shape metadata (dimensions array). No element copying or traversal.
- How many times: Constant time, independent of array size (n).
As the number of elements grows, the time to reshape stays roughly constant.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 5 operations |
| 100 | About 5 operations |
| 1000 | About 5 operations |
Pattern observation: The time is constant regardless of the number of elements.
Time Complexity: O(1)
This means the time to reshape is constant and does not grow with the number of elements. MATLAB reshape updates metadata without copying data.
[OK] Correct thinking: "Reshaping is instant and does not depend on array size."
[X] Why the wrong one fails: Reshape does not copy or process elements; it only updates metadata, so no O(n) cost.
Understanding how reshaping scales helps you reason about data manipulation efficiency in real tasks.
"What if we reshape a very large array multiple times in a loop? How would the time complexity change?"