You may have heard that vectorizing your code is a cornerstone of
achieving the best performance from both MATLAB® and Star-P code.
But what does "vectorizing" mean? Simply put, vectorizing
your code means that you avoid using “for” loops to
operate on individual elements of a vector or array. Instead, you
operate upon vectors and arrays as entire units using MATLAB's built-in
functions. The following are two quick examples demonstrating ways
to vectorize in common situations. (The lines which change upon
vectorization have been highlighted in blue.)
First, consider a simple example illustrating what vectorization
is about. Instead of calculating each element of a matrix using
nested loops, here can calculate it quickly by operating on the
entire matrix v at once:

NOT Vectorized:
% Bad: calculate matrix with for
loop
% Note: may take hours if not vectorized!
v=rand(1000*p);
vs=zeros(1000*p);
for i=1:size(v,1)
for j=1:size(v,2)
vs(i,j) = sin(v(i,j));
end
end
Vectorized:
% Good: calculate matrix with built-in
v=rand(1000*p);
vs_vec = sin (v);

Next, let’s consider a relatively common occurrence:
a conditional statement inside a for loop.
- Instead of checking the condition "less than zero"
for each element by looping (top), a single vectorized sweep
(bottom) is carried out. This yields a vector 'idx' which holds
a value 1 (true) or 0 (false) for each element.
- Vectorized logical indexing is performed (bottom). An element
a(i) is set to zero if 'idx(i)' is true.
NOT Vectorized:
% Bad: conditional inside for loop
numpoints = 10000;
a = 2*rand(numpoints*p, 1)-1;
for i = 1:numpoints
if (a(i) < 0)
a(i) = 0;
end
end
Vectorized:
% Good: vectorized conditional
numpoints = 10000;
a = 2*rand(numpoints*p, 1)-1;
idx = (a < 0);
a(idx) = 0;

|