cs249 lecture notes, Fall 2001 Week 5, Monday Quiz 3 Homework 4 due Wednesday 10 October Homework 4 ---------- Here are some debugging tips that might make life easier: 1) Start with a working program. Make small changes at a time, and then run the program again. If there is an error, you have a pretty good idea where it is! 2) If the program runs into an error, reduce the level of recursion to the simplest level that causes the error. This will simplify the debugging effort. 3) If you know what variable is causing the error, try displaying the value of that variable when it gets assigned, or when it gets passed as an argument. 4) Inside a function, it is often useful to add a line right at the beginning that displays the values of the arguments. Vectors ------- MATLAB syntax >> v = [3, 4] >> v(1) ans = 3 >> v(2) ans = 4 >> norm (v) ans=5 Vector arithmetic division by a scalar function vn = normalize (v) vn = v / norm (v); end addition, substraction function vp = perpendicular (v) vp = [-v(2), v(1)]; end Drawing Koch curves with two-dimensional vectors Fundmental theorem in linear algebra: given any two (non-parallel) vectors in 2-space, you can describe any other vector as a linear combination of the two. Drawing lines ------------- Foreshadowing of matrics function drawline (v1, v2) z = [v1;v2]; line (z(:,1), z(:,2)) end function triangle (v1, v2, v3, color) z = [v1;v2;v3]; fill (z(:,1), z(:,2), color) end Recursion --------- function countdown (n) if n == 0 disp ('Blastoff!') else disp (n) countdown (n-1) end end Draw a workspace diagram for this sequence of function invocations. Have a look at snow.m function draw_snow (v1, v2, n) if (n == 0) drawline (v1, v2); return end v = v2 - v1; p1 = v1 + v / 3; p2 = v1 + 2 * v / 3; p3 = v1 + v / 2; length = norm (v); height = length/3 * sqrt(3)/2; p4 = p3 + height * normalize (perp (v)); draw_snow (v1, p1, n-1); draw_snow (p2, v2, n-1); draw_snow (p1, p4, n-1); draw_snow (p4, p2, n-1); end Notice that unless n==0, we don't draw any lines at all! We just compute some intermediate values and make recursive calls.