# Vectorization

### From ComputingForScientists

## Contents |

# 1. Problems

## 1.1. Efficiency

clear N = 100000; tic(); for i = 1:N A(i) = i; end fprintf('Time to populate %d element array without pre-allocation: %.5f\n',N,toc()); clear N = 100000; tic(); A = zeros(N,1); for i = 1:N A(i) = i; end fprintf('Time to populate %d element array with pre-allocation: %.5f\n',N,toc()); clear N = 100000; tic(); A = [1:N]; fprintf('Time to populate %d element array using colon operator: %.5f\n',N,toc());

## 1.2. Replacing vectorization with `for`

loops

Write a program that uses one or more `for`

loops to produce the same arrays `x`

and `y`

as created using the following program. In your program, anything to the right of an equal sign should be a scalar (e.g., `x = [0,0.1,0.2,0.3]`

is not allowed, but `z = 1`

is).

x = [0:0.1:1]; y = x.^2;

Answer |
---|

for i = 1:11 x(i) = (i-1)/10; y(i) = x(i)*x(i); end |

## 1.3. Replacing vectorization with `for`

loops

Write a program that uses one or more `for`

loops to produce the same arrays `x`

and `y`

as created using the following program. In your program, anything to the right of an equal sign should be a scalar (i.e., `x = [0,2,4]`

is not allowed).

clear; x = [0:2:100]; y = x.^2+1;

Answer |
---|

i = 0; while i < 51 x(i) = 2*i; y(i) = x(i)*x(i) + 1; i = i+1; end Also accepted for i = 0:2:100 x(i) = i; y(i) = x(i)*x(i) + 1; end |

## 1.4. Replacing vectorization with `for`

loops

Write a program that uses one or more `for`

loops to produce the same arrays `x`

and `y`

as created using the following program. In your program, anything to the right of an equal sign should be a scalar (e.g., `x = [0,0.1,0.2,0.3]`

is not allowed, but `z = 1`

is).

x = [0:0.1:1]; y = x.^2;

Answer |
---|

for i = 1:11 x(i) = (i-1)/10; y(i) = x(i)*x(i); end |

## 1.5. `sum`

Without the use of a `for`

or `while`

statement, replace everything after the first line in the program below with one or more statements that produce the same final value of `s`

. Your program should work the same if the `A`

is changed to have more values.

clear; A = [0:0.5:1]; s = 0; for i = 1:length(A) s = s + i; end s

Answer |
---|

First, write out in long-hand When A has three elements s = 0 s = 0 + 1 = 1 % 1 s = s + 2 = 1 + 2 % 3 s = s + 3 = 1 + 2 + 3 % 5 When A has four elements s = 0 s = 0 + 1 = 1 % 1 s = s + 2 = 1 + 2 % 3 s = s + 3 = 1 + 2 + 3 % 5 s = s + 4 = 1 + 2 + 3 + 4 % 9 Answer: s = sum([1:length(A)]); |

## 1.6. `sum`

Without the use of a `for`

or `while`

statement, replace everything after the first line in the program below with one or more statements that produce the same result for `s`

. Your program should work the same if the elements in array `A`

are changed.

A = [0:0.5:1]; s = 0; for i = 2:length(A) s = s + A(i) + A(i-1); end s

Answer |
---|

s = sum(A(2:end)) + sum(A(1:end-1)) |