cs249 lecture notes, Fall 2001 Week 3, Monday Homework 1 due, Homework 2 assigned (Due next Monday). Read Chapter 3 for Thursday. Workspace --------- A workspace is a collection of variables. The who command prints the names of the variables in the current workspace. The clear command removes a variable from the workspace. Script files and function files ------------------------------- Both called m-files. Both stored in your m-file directory. In both cases, you add the directory to the path. Section 1.7: scripts A script is just a list of commands (see fred.m) You execute the script by typing the name (without the .m) The script can access whatever variables are defined. Section 2.7: function files If the first word of an m-file is "function" it defines a new function. See square.m for syntax. The arguments you provide when you invoke a function are assigned to the input variables (in order). When the function assigns a value to the output variable, that value becomes the "return value" Example: square (3) Functions and workspaces ------------------------ Calling a function creates a new workspace. The input and output variables are in the new workspace. The variables you create in the body of the function are in the new workspace. When the function ends, the new workspace disappears. The only traces of the function are: 1) whatever side-effect the function had, like displaying a value or creating a plot 2) the return value. Calling functions ----------------- When you call a function, you almost always want to use the result for something 1) assign it to a variable 2) use it as part of an expression 3) use it as an argument to another function Function comments ----------------- Comments begin with % and go to the end of the line Any comment that appears immediately after the function line is the documentation of the function. The documentation gets printed when you type "help functionname" Workspace diagrams ------------------ function c = pythagoras (a, b) sum_squares = a^2 + b^2; c = sqrt (sum_squares) 1) you can have variables with the same name in different workspaces 2) if you use a variable as an argument, the name of the variable has nothing to do with the name of the input variable 3) if you assign the result of a function call to a variable, the name of the variable has nothing to do with the output variable Exercise: write a function that takes two points and computes the distance between them.