Introductory Programming Fall 2005 For today you should have 1) turned in Evaluation 4 if you haven't For next time you should 1) review Chapter 3 2) prepare for an Evaluation -- I will ask you to write a function Evaluation 4 Notes ------------------ Vocabulary is important! scalar, matrix, vector, array, index expression, statement read, write Don't forget what an assignment statement is!!! In a simulation, time can be a confusing thing. The value of the parameter V varies in simulated time, but the matrix B in the program is set once and then read, but not written. Each time through the loop, we change one of the elements of t and N. At the end, we have a vector that contains successive values of t and N. Think of a for loop as having a before, during, and after. before happens once, after happens once during happens once per iteration. Debugging a loop: display relevant values at the top of the loop. Let's construct a solution. Functions --------- Create a script named square.m, and type in the following program function y = square (x) % SQUARE Computes x raised to the second power. y = x^2 The word function at the beginning indicates that this is a function file, which is different from the script files we have been working with: 1) after you define a function in a function file, you call (or invoke) it as if it were a build-in function z = square(3) What happens if you try to call it like a command? square 2) functions take arguments, also known and parameters, also known as input variables square(3) a = 5 square(a) square(a+1) Notice that the argument you provide can be any expression. It doesn't have to be a variable named x. Inside the function, x refers to whatever value you provide. 3) functions have their own, private workspace! If you create a local variable named a: function y = square (x) a = 3 y = x^2 It disappears when the function finishes. square(5) a 4) You get information back from a function in an output variable. z = square(5) The output variable is named y. When you set y, you set the return value. When you call the function, you can do anything you want with the return value. y = square(5) z = square(5) w = sqrt(square(5)) A model of the execution of a function 1) evaluate the argument (which is an expression) 2) assign the resulting value to the input variable 3) run the body of the function 4) the value of the output variable is the return value 5) replace the original function call with the return value 6) resume whatever you were doing when you got to the function call.