Categories:

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.

Posted in Tutorials. Tagged with , , .

## 4 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

1. Unfortunately, C++ would never have any idea what to do here. Ruby however…

``` i = 0 while i < 4 str << "Shots! " i = i + 1 end print str ```

You can…
`"Shots! " * 4 #=> "Shots! Shots! Shots! Shots! "`

2. and in python

```>> "shots " *4
'shots shots shots shots '
>>>
```
3. Do this two snippets of code really generate the same results? The first snippet will take longer not only due to the lack of vectorization, but because you redefine mole N times. I’m confused.

4. doodah,
thanks for the reply; the codes are not the same because of the rand() generated points for each case. Also I do not change mol N times but I did notice that the index within the if statement should be i and not 1:1000.