Row and column vectors in MATLAB - Time & Space Complexity
We want to understand how the time it takes to work with row and column vectors changes as their size grows.
Specifically, how does the time to create or access elements in these vectors grow when the vector gets longer?
Analyze the time complexity of the following code snippet.
% Create a row vector with n elements
n = 1000;
rowVec = 1:n;
% Create a column vector with n elements
colVec = (1:n)';
% Access each element in the row vector
for i = 1:n
val = rowVec(i);
end
This code creates row and column vectors of size n and then accesses each element in the row vector one by one.
- Primary operation: Accessing each element of the row vector inside the for-loop.
- How many times: The loop runs n times, once for each element.
As the vector size n grows, the number of element accesses grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 element accesses |
| 100 | 100 element accesses |
| 1000 | 1000 element accesses |
Pattern observation: The number of operations grows directly in proportion to the size of the vector.
Time Complexity: O(n)
This means the time to access all elements grows linearly as the vector gets longer.
[X] Wrong: "Accessing elements in a row vector is faster than in a column vector because of their shape."
[OK] Correct: Both row and column vectors store elements in memory similarly, so accessing each element one by one takes the same amount of time.
Understanding how vector size affects operation time helps you explain efficiency clearly and shows you know how data layout impacts performance.
"What if we accessed elements in a column vector inside the loop instead of a row vector? How would the time complexity change?"