Element-wise operations (.*, ./, .^) in MATLAB - Time & Space Complexity
When we use element-wise operations in MATLAB, we want to know how the time to finish changes as the data gets bigger.
We ask: How does the work grow when we multiply, divide, or power each element in arrays?
Analyze the time complexity of the following code snippet.
A = rand(1, n);
B = rand(1, n);
C = A .* B; % element-wise multiplication
D = A ./ B; % element-wise division
E = A .^ 2; % element-wise power
This code creates two arrays of size n and performs element-wise multiplication, division, and squaring on them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Element-wise arithmetic on each array element.
- How many times: Once for each of the n elements in the arrays.
Each element in the arrays is processed one time, so the total work grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: Doubling the input size roughly doubles the work needed.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of elements.
[X] Wrong: "Element-wise operations are instant and do not depend on array size."
[OK] Correct: Each element must be processed one by one, so bigger arrays take more time.
Understanding how element-wise operations scale helps you explain performance when working with large data in MATLAB.
"What if we replaced element-wise operations with matrix multiplication? How would the time complexity change?"