cs249 lecture notes, Fall 2001 Week 3, Thursday Homework 2 due on Monday Finish Chapter 3 for Monday. Quiz Monday on Chapter 3. Homework 1 feedback ------------------- Out of 4: 1 for each part, one for presentation and discussion. Write a paper, and include numbers, code, figures, and MATLAB output as appropriate. The object of the game is not to provide evidence that you did what you were told. It is to explain what you learned from the experiment. There should be more words than numbers. Functions revisited ------------------- Exercise: write a function that takes two points and computes the distance between them. function d = distance (x1, y1, x2, y2) d = pythagoras (x1 - x2, y1 - y2); end function c = pythagoras (a, b) sumSquares = square(a) + square(b); c = sqrt (sumSquares); end function s = square (x) s = x^2; end Flow of execution ----------------- A function call is a detour in the flow of execution 1) evaluate the arguments 2) assign the values of the arguments to the input variables 3) execute the statements in the body of the function Root finding ------------ Given some f(x), find x such that f(x) = 0. For simple f(x), we can find the answer by algebra. Otherwise, not so easy. But if we can evaluate f(x) and its derivative, we can approximate the root. See diagram page 3-2. x1 = x0 - f(x0) / f'(x0) Square roots ------------ The square root of a is the value of x such that x^2 = a In other words f(x) = x^2 - a = 0 f'(x) = 2x Plugging f(x) and f'(x) into Newton's formula yields x1 = 1/2 (x0 + a/x0) And we've already seen how well that works! for loops --------- for j = 1:5 disp (j); end strings ------- So far, only one type of value, numeric. String values are enclosed in single quotes: >> t = 'Hello'; Annoyingly, when MATLAB prints a value it doesn't indicate the type: t = Hello Which can be confusing if you have a String that contains numbers: >> x = 123 x = 123 >> y = '123' y = 123 >> x+1 ans = 124 >> y+1 50 51 52 (Note typographical error on page 3-6) String concatenation -------------------- The [ ] operator performs string concatenation >> s = 'Hello, ' >> t = 'World!' >> [s t] ans = Hello, World! Displaying values ----------------- 1) No semi-colon on an assignment 2) disp (expression) 3) fprintf fprintf (FORMAT STRING, arg1, arg2, arg3...) Format string contains escape sequences that begin with % Each sequence prints the next arg in the list. Sequence controls the format. Have to have the right number of arguments. \t prints a tab character \n prints a newline character Subfunctions ------------