hw3_solutions - Due: September 18, 2008 CS 257 (Luke...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Due: September 18, 2008 CS 257 (Luke Olson): Homework #3 Problem 1 [Puzzled] You are profling a loop in your numerical code at work with the Following snippet: Listing 1: ±irst 1 function t = test1 ( n ) 2 3 tic ; 4 5 x(1) = 150; 6 for i=2:n 7 x(i) = .99 * x(i-1); 8 end 9 10 t = toc ; However, it is noticed that this piece is very slow as n increases. O²er a fx ( hint: one line ) that speeds up your code. Hand in the solution, a comparative timing showing the speedup, and a short explanation . Solution At each iteration, say i , the vector x has size i . On the next iteration, in accessing position i + 1, Matlab must reallocate memory For a new array oF size i + 1 and copy the values into the new array. Summing over n iterations, we have n i =1 i = n ( n + 1) / 2 = O ( n 2 ) . To remedy the situation, since we know how large the vector will be beFore hand, we can preallocate the vector as Follows Listing 2: ±ixed 1 function t = test2 ( n ) 2 3 tic ; 4 5 x = zeros (n,1); %Preallocate 6 7 x(1) = 150; 8 for i=2:n 9 x(i) = .99 * x(i-1); 10 end 11 t = toc ; 12 13 end Preallocation allows us to access the vector in contiguous memory locations and we will not need to reallocate space at each step. Grading 1.5 points For correct reason, 1 point For fx. Page 1 oF 6
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Due: September 18, 2008 CS 257 (Luke Olson): Homework #3 Problem 2 [Storage] While profling another portion oF code ( mat-vec.m ) you implement two versions oF a matrix- vector multiply (
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 07/10/2011 for the course CS 257 taught by Professor Olson during the Spring '08 term at University of Illinois, Urbana Champaign.

Page1 / 6

hw3_solutions - Due: September 18, 2008 CS 257 (Luke...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online