Vectorization

From ComputingForScientists

Jump to: navigation, search

Contents

  1. Problems
    1. Efficiency
    2. Replacing vectorization with for loops
    3. Replacing vectorization with for loops
    4. Replacing vectorization with for loops
    5. sum
    6. sum

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;

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;

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;

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

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
Personal tools