
278 Ñ Efficient Coding Using Vectorization Technique
Let us now consider the vectorized implementation of the code. The “for” loop used to
determine if the counter value is divisible (i.e., loop corresponding to for i = 1:no_
found) can be vectorized as shown in the code here:
kprime_mod3.m
function val_arr = kprime_mod3(k)
% Vectorized version
val_arr = 2*ones(1,k);
% Pre-assign val_arr to be a array of ’’s
% Since counter would be divided by val_arr
% elements, all the elements are initialized to
% 2 and not 1
counter = 3;
no_found = 1;
while no_found < k % Loop till k primes are found
if all(rem(counter,val_arr(1:no_found)))
no_found = no_found ...