Vectorization helps you do many calculations at once, making your code faster and simpler. Loops do one step at a time, which can be slower.
0
0
Vectorization vs loops in MATLAB
Introduction
When you want to add two lists of numbers quickly.
When you need to apply the same math to every item in a big list.
When you want your program to run faster by avoiding repeated steps.
When you want your code to be shorter and easier to read.
When working with large data sets like images or signals.
Syntax
MATLAB
Loop example: for i = 1:length(A) B(i) = A(i) * 2; end Vectorized example: B = A .* 2;
Loops repeat commands for each item one by one.
Vectorization applies operations to whole arrays at once.
Examples
This loop squares each element of A one by one.
MATLAB
A = [1, 2, 3, 4]; B = zeros(size(A)); for i = 1:length(A) B(i) = A(i)^2; end
This vectorized code squares all elements of A at once.
MATLAB
A = [1, 2, 3, 4]; B = A.^2;
Loop with condition: multiply elements greater than 2 by 10.
MATLAB
A = [1, 2, 3, 4]; B = zeros(size(A)); for i = 1:length(A) if A(i) > 2 B(i) = A(i) * 10; else B(i) = A(i); end end
Vectorized version with condition using logical indexing.
MATLAB
A = [1, 2, 3, 4]; B = A; B(A > 2) = A(A > 2) * 10;
Sample Program
This program shows how to double numbers in a list using a loop and vectorization. Both give the same result, but vectorization is simpler.
MATLAB
A = 1:5; % Using loop to double each element B_loop = zeros(size(A)); for i = 1:length(A) B_loop(i) = A(i) * 2; end % Using vectorization to double each element B_vector = A .* 2; % Display results fprintf('Using loop: '); fprintf('%d ', B_loop); fprintf('\nUsing vectorization: '); fprintf('%d ', B_vector); fprintf('\n');
OutputSuccess
Important Notes
Vectorized code usually runs faster in MATLAB because it uses optimized math operations.
Loops are easier to understand for beginners but can be slower for big data.
Use vectorization when possible, but loops are fine for complex steps that can't be vectorized.
Summary
Vectorization applies operations to whole arrays at once, making code faster and shorter.
Loops repeat commands step-by-step and can be slower but are sometimes necessary.
In MATLAB, prefer vectorization for better performance and cleaner code.