The first time I heard of vectorizing loops in MATLAB was in a Convection Heat Transfer class where the project required thousands of iterations before the system would converge. In order for this to happen in a timely matter, it was important to vectorize iterations where applicable.
The following example randomly places points at different locations. The first 1000 points are then changed to another location. Finally, there is a count to see how many points are less than .5.
Observe the two code snippets
First, using a ‘for’ and ‘if’ statement.
tic; clear; N = 1e6; % Number of points mol = zeros(N,1); mol = rand(N,1); for i = 1:N % Change first 1000 elements if i <= 1000 mol(i) = 2*rand()-1; end if mol(i) < .5 count = count+1; end end % Print result fprintf('Number of points < .5 = %f\n',count) toc;
And now the vectorized version
tic; clear; N = 1e6; % Number of points mol = rand(N,1); % Change first 1000 points mol(1:1000) = 2*rand()-1; % Check for points less than .5 count = sum (mol < .5 ); % Print result fprintf('Number of points < .5 = %f\n',count) toc;
The vectorized code besides using less number of lines will also run quicker. Observe also that there are no for nor if statements in the second code. It should be pretty easy to see where the vectorization comes into play. Be sure to leave a comment and perhaps show off your vectorized code.