0
0
MATLABdata~5 mins

Vectorization vs loops in MATLAB - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Vectorization vs loops
O(n)
Understanding Time Complexity

We want to see how using vectorization or loops affects how long a MATLAB program takes to run.

How does the time needed change when we do the same task with loops versus vectorized code?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

n = 1000;
result = zeros(1,n);
for i = 1:n
    result(i) = i^2;
end

% Vectorized version
result_vec = (1:n).^2;

This code calculates the squares of numbers from 1 to n using a loop and then using vectorization.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop runs from 1 to n, doing one multiplication each time.
  • How many times: The loop runs exactly n times.
  • Vectorized operation: The whole array is squared in one step without explicit looping.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations (Loop)Approx. Operations (Vectorized)
1010 multiplications1 vector operation on 10 elements
100100 multiplications1 vector operation on 100 elements
10001000 multiplications1 vector operation on 1000 elements

Pattern observation: The loop does more steps as n grows, while vectorization handles all at once, so it grows slower in time.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of elements when using loops, but vectorization can be faster by doing many operations together.

Common Mistake

[X] Wrong: "Vectorization always means the program runs in constant time no matter how big n is."

[OK] Correct: Vectorization still processes all elements, so time grows with n, but it uses faster internal operations than loops.

Interview Connect

Understanding how loops and vectorization affect time helps you write faster MATLAB code and shows you can think about efficiency clearly.

Self-Check

"What if we replaced the loop with a nested loop that squares numbers in a 2D matrix? How would the time complexity change?"