Why Vectorize: Replacing Loops with Array Operations
Vectorization means expressing an operation as a single array-wide command instead of an explicit for-loop over individual elements; because MATLAB's interpreter has per-iteration overhead, a vectorized statement like y = sin(x) applied to an entire vector x is typically far faster than looping and calling sin(x(i)) one element at a time, in addition to being shorter and easier to read.
Cricket analogy: Vectorizing sin(x) over a whole vector at once is like a stadium's electronic scoreboard updating every player's strike rate simultaneously after a match, rather than a scorer manually recalculating one player's figures at a time, over by over.
Implicit Expansion (Broadcasting)
Since MATLAB R2016b, arithmetic operators automatically broadcast, or implicitly expand, operands of compatible but different sizes: adding a 3x1 column vector to a 1x4 row vector produces a 3x4 matrix where every combination of elements is summed, without needing an explicit repmat call. Two dimensions are broadcast-compatible if they are equal or one of them is 1; a 3x1 and a 1x4 combine because each mismatched dimension has a 1 on one side.
Cricket analogy: Broadcasting a 3x1 column of bowler economy rates against a 1x4 row of over-numbers to produce a 3x4 combined matrix mirrors instantly cross-tabulating every bowler's performance against every over of a match without manually pairing each combination.
Common Vectorization Idioms
Beyond simple elementwise math, vectorization extends to conditional logic (using logical indexing instead of if-inside-a-loop), accumulation (using sum, cumsum, prod instead of running totals in a loop), and functional application (arrayfun/cellfun for per-element function calls that can't be simply vectorized). bsxfun still works for broadcasting on older MATLAB versions but is now largely redundant since implicit expansion was introduced.
Cricket analogy: Using cumsum on ball-by-ball runs to get a running total mirrors a live scoreboard's running score, updated instantly for the whole innings at once instead of a scorer adding one ball's runs at a time.
x = linspace(0, 2*pi, 1000);
% Vectorized (fast)
y = sin(x);
% Non-vectorized equivalent (slow, avoid)
y2 = zeros(size(x));
for k = 1:numel(x)
y2(k) = sin(x(k));
end
% Implicit expansion / broadcasting (R2016b+)
col = [1; 2; 3]; % 3x1
row = [10 20 30 40]; % 1x4
M = col + row; % 3x4 result, every pairwise sum
% Logical indexing instead of loop+if
data = [-2 5 -1 8 0 -3];
positives = data(data > 0); % [5 8]
% Accumulation without a loop
running = cumsum(data);Two array dimensions are broadcast-compatible if they are equal or one of them is 1. A 3x1 plus a 1x4 works, producing a 3x4 result; a 3x1 plus a 1x5 also works; but a 3x2 plus a 1x4 fails because neither the 3-vs-1 pairing nor the 2-vs-4 pairing satisfies the rule on both dimensions simultaneously.
Implicit expansion can silently produce a much larger matrix than intended if you accidentally add a column vector to a row vector instead of two same-shaped vectors — check sizes with size() when a result unexpectedly balloons to an NxM matrix instead of the elementwise Nx1 result you meant.
- Vectorization replaces explicit for-loops with whole-array operations, which is faster and more concise in MATLAB.
- Implicit expansion (broadcasting), standard since R2016b, automatically expands operands whose dimensions are equal or 1.
- Logical indexing (data(data>0)) replaces if-inside-a-loop filtering.
- cumsum, sum, and prod replace manual running-total loops.
- arrayfun/cellfun handle per-element function calls that resist direct vectorization.
- bsxfun is now largely redundant, superseded by automatic implicit expansion.
- Unexpected broadcasting can silently create a much larger result than intended — verify with size().
Practice what you learned
1. Why is y = sin(x) generally preferred over a for-loop calling sin(x(i)) for each element?
2. What is the result shape of adding a 3x1 column vector to a 1x4 row vector under implicit expansion?
3. Which rule determines whether two dimensions are broadcast-compatible?
4. What does data(data > 0) accomplish?
5. What is bsxfun's relationship to implicit expansion today?
Was this page helpful?
You May Also Like
Matrices and Vectors in MATLAB
Learn how MATLAB represents scalars, vectors, and matrices as a single unified array type, and how to construct them with literals and built-in functions.
Indexing and Slicing in MATLAB
Master subscript and linear indexing, colon-based slicing, the end keyword, and logical indexing to access and filter matrix data efficiently.
Matrix Operations and Linear Algebra
Understand the distinction between matrix and element-wise operators, solve linear systems with backslash, and compute determinants, inverses, and eigenvalues.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics