CS99, Fall 2002 Mon 11/11 Lecture 11 ------------------------------------------------------------------------------- (0) Announcements + Prelim 2 on 11/19 + Final project ("Bahggle") ------------------------------------------------------------------------------- (1) Overview + programming language - words/tokens + data types + data structures - sentences/statements + selection + repetition + others? + functions - justification - syntax - how/when to use ------------------------------------------------------------------------------- (1) Case study: rolldice1.m + strengths? + weaknesses? ------------------------------------------------------------------------------- (2) Improved case study: rolldice2.m + strengths? + weaknesses? ------------------------------------------------------------------------------- (3) Justification of functions + goal: - modular programs (small chunks) - develop "black boxes" to perform repetitive tasks + good style: - clarity -- avoids "spaghetti code" - reduced redundancy in code + debugging and development - iterative refinement - testing by parts + code reuse: - reduced redundancy in *time* to program - can share code ------------------------------------------------------------------------------- (4) Current Approach: Script M-files + definition of SCRIPT: - the M-files you've written so far - collection of commands that you could have entered at the prompt - see scripthelp.txt online + approach: - write "little" subprograms - store them in different m-files - call the programs when necessary, but ensure path is set - invoke by using the script name as a command - use EVAL: ex) >> eval('scriptname') + visibility of variables (called SCOPE) - all scripts share vars of other scripts - called GLOBAL VISIBILITY ex) restore.m s1.m s2.m +--------+ +----------+ +--------+ | clear | | restore | | s1; | | clc | | x=1; | | x=x+1; | +--------+ | pause | +--------+ +----------+ >> s2; x; restore Output? ------------------------------------------------------------------------------- (5) New Approach: Function M-files + math definition: - correspondance of two sets - given input of value from one set produces a value from the other set ex) square root of 4 input: 4, which belongs to set of real numbers output: 2, which belongs to set of real numbers + programming definition: - the gist: sequence of steps to do task - name(inputs): given inputs, get output(s) ex) >> 1 + sqrt(4) >> randInt(0,1) >> x = input('enter something') - functions can be math or task! - *MATLAB* functions can zero-many inputs and zero-many outputs -------------------------------------------------------------------------------