Vectorization


Fourier Series as 2 loops: TwoLoop.m
Replace inner loop with  u'*v: OneLoop.m
Replace loops with (u*v')*a: NoLoop.m
Run timing experiment: VecExp.m

How to use these functions & cookie challenge

  1. The "Loop" functions take two inputs: an n-by-1 array of coefficients (a) and a p-by-1 array of times (t), and return one output: p -by-1 array (x). So, if a & t are defined, you can call TwoLoop (or any of the others "x=TwoLoop(a,t);".
  2. We're not really interested in the answers, just how long it takes. We can create random arrays using the rand command: a=rand(10,1) would create a 10-by-1 array of random numbers (uniform distribution on [0 1]). For timing functions, Matlab provides two functions "tic" and "toc." When tic is called, Matlab sets a timer to zero. A call to toc returns the time since the last call to tic. So, "tic;x=TwoLoop(a,t);time=toc;" would compute how long it takes to compute one call to TwoLoop (with inputs a and t), storing the time (in seconds) in toc.
  3. We can now design an experiment to compare the performance of the three Loop functions. The idea is to define N, an array of sizes for a and t. Then, for each value in N, we create a random a & t of this size and compare the times of the three functions. As with any experiment, averaging over several trials is a good idea. So, for each N, we should call each Loop function several times and compute the average time. This experiment is implemented in VecExp.m. To use VecExp, create a vector of sizes, say "N=[10 100 500 1000];". Then, "Times=VecExp(N,10);" will compute the time for each function with inputs of size N, averaged 10 times. Times will have a row for each entry in N and three columns. So, in this example, Times(3,1) is the average time to solve the problem using TwoLoop with length(a)=length(t)=500 (N(3)). Times(3,2)and Times(3,3) would be the comparable times for OneLoop and NoLoop, respectively.
  4. Cookie Challenge: Find a very simple fix that makes NoLoop always faster than OneLoop, using N as defined above. The first person to e-mail me an answer before class on Monday will receive one, large CTB cookie. If no one sends me the answer, you will have to watch me eat the cookie while I explain the answer.