Lab 4.ppt [兼容模式]csyliu/course/comp319/Lab/Lab4.pdfThe section for most functions involves...
Transcript of Lab 4.ppt [兼容模式]csyliu/course/comp319/Lab/Lab4.pdfThe section for most functions involves...
Lab 4 of COMP 319Lab 4 of COMP 319
User-defined Functions
Lab tutor : Dennis Yang LIU
Email : [email protected]
Lab 4 : Oct. 9, 2014
1
Review of Lab 3
E ti t lExecution control
Conditional execution• if statements• switch statements
It ti Iteration• for loops• while loops
2
Outline of Lab 4
• Objectives of Lab 4
• Concept of user-defined functionsp
• Storing and using functions
Ad d kill R i• Advanced skill: Recursion
3
Outline of Lab 4
• Objectives of Lab 4
• Concept of user-defined functionsp
• Storing and using functions
Ad d kill R i• Advanced skill: Recursion
4
Objectives of Lab 4
• Writing a user-defined function allows you to isolate and package together a code block, so you can apply that code block to different sets of input data. p
• We have already made use of some built-in functions such as sin() and max() by calling them. This course will deal () () y gwith creating and using your own functions.
5
Objectives of Lab 4
• This lab discusses the nature, implementation, andThis lab discusses the nature, implementation, and behavior of user-defined functions in Matlab:
– How to define a functionow o de e u c o
– How data are passed into a function
H d i l di l i l l– How to return data including multiple results
– How to include other functions into your own function
6
Outline of Lab 4
• Objectives of Lab 4
• Concept of user-defined functionsp f f f
• Storing and using functions
Ad d kill R i• Advanced skill: Recursion
7
Concept of user-defined functions
• A function is an implementation of• A function is an implementation of
procedural abstraction; and
encapsulation
8
Procedural abstraction
• Procedural abstraction is the concept that permits a code block that• Procedural abstraction is the concept that permits a code block that solves a particular sub-problem to be packaged and applied to different data inputs.
• We have already used a number of built-in procedural abstractions in the form of functions. All the mathematical functions that compute, for example, the sine of a collection of angles or the maximum value of a
d l b i Th ll l dvector, are procedural abstractions. They allow us to apply a code block about which we know nothing to data sets that we provide.
• To make use of a built-in function, all we have to do is provide data inTo make use of a built in function, all we have to do is provide data in the form the function expects, and interpret the results according to the function’s specification.
9
Procedural abstraction
10
Encapsulation
• Encapsulation is the concept of putting a wrapper• Encapsulation is the concept of putting a wrapper around a collection that you wish to protect from outside influence. Functions encapsulate the code they contain in two ways:
1. The variables declared within the function are not visible from elsewhere; andfrom elsewhere; and
2. The function’s ability to change the values of variables is restricted to its own body.
11
Black box view of a function
<Item 1> <Item 2> <Item n>
Param 1 Param 2 Param n<name>
ResultResult
• The black box consists of two parts: the definition of the interface by which the user passes data items to and from the function; and the code block that produces the results required by that interface.
12
Black box view of a function
<Item 1> <Item 2> <Item n>
Param 1 Param 2 Param n<name>
ResultResult
• A function definition consists of the following components:– A name that follows the same syntactic rules as a variable name;– A set of 0 or more parameters provided to the function;
13
– Zero or more results to be returned to the called of the function.
Black box view of a function
<Item 1> <Item 2> <Item n>
Param 1 Param 2 Param n<name>
Result
h b i i f f i b i b f i f h f i
Result
• The basic operation of a function begins before execution of the function actually starts. If the function definition requires n parameters, the calling instructions first prepare n items of data from its workspace to be provided. These data are then passed to the function, the code body is
14
provided. These data are then passed to the function, the code body is executed, and the results are returned to the caller.
Template of a function definition
function <return info> <function name> (<parameters>)function <return info> <function name> (<parameters>)<documentation>
<code body> % must return the results
1. The <return info> section for most functions involves providing the name(s) of the results returned followed by an = sign. If more than one result is to be returned, they are defined in a vector like container. If nothing is to be returned from this function, both the result list and the = sign are omitted.
2. The <function name> is a name with the same syntactic rules as a variable name, and will be used to invoke the code body.
15
Template of a function definition
function <return info> <function name> (<parameters>)function <return info> <function name> (<parameters>)<documentation>
<code body> % must return the results
3. The <parameters> section is a comma-separated list of the names of the data to be provided to the function.
4. The <documentation> section is one or more lines of comments that describe what the function does and how to call it. These lines will appear in the following situation:– All the documentation lines up to the first non-document line are printed
in the command window when you type the following:>> help <function name>
16
A function example
1 function volume = cylinder(height radius)1. function volume = cylinder(height, radius)2. % function to compute the volume of a cylinder3. % volume = cylinder(height, radius)4 base pi * radi s^2;4. base = pi * radius^2;5. volume = base * height;6.
• Line1: the Matlab function definition is introduced by the key word function, followed by the name of the return variable (if any) and the
i= sign.• Line2: all comments written immediately after the function header
are available to the command window when you enter:
17
>> help cylinder
A function example
1 function volume = cylinder(height radius)1. function volume = cylinder(height, radius)2. % function to compute the volume of a cylinder3. % volume = cylinder(height, radius)4 base pi * radi s^2;4. base = pi * radius^2;5. volume = base * height;6.
• Line3: it is a good idea to include in the comments a copy of the function header line to remind a user exactly how to use this f tifunction.
• Line5: you must make at least one assignment to the result variable.• Line6: the function definition needs no end statement. The code body
18
terminates automatically at the end of the file.
Outline of Lab 4
• Objectives of Lab 4
• Concept of user-defined functionsp
• Storing and using functions
Ad d kill R i• Advanced skill: Recursion
19
Storing Matlab functions
• All Matlab functions must be created like scripts in an m-file. When the file is first created, it must be saved in an m-file with the same file name as the function. For example, the function
li d t b d i fil d li dcylinder must be saved in a file named cylinder.m.
• Matlab functions must be stored in a separate file located in a directory accessible to any script or function that calls it. For the general user, the current directory is the normal place to store the function.
20
Storing Matlab functions
21
Storing Matlab functions
22
Using Matlab functions
O th fil h b d i k• Once the file has been saved, you may invoke the function by entering its name and parameter of the correct type and number in the command window, in a script, or in other function definitions. If you do not specify an assignment for the result of the function call it will befor the result of the function call, it will be assigned to the default variable ans.
23
Testing and using Matlab functions
Do it yourself
• Enter the following commands in the command window.
>> help cylinderfunction to compute the volume of a cylindervolume = cylinder(height, radius)y ( g )
>> cylinder(1,1)ans =ans =
3.1416
24
Returning multiple results
• Matlab is unique among programming languages in• Matlab is unique among programming languages in providing the ability to return more than one result from a function. The multiple results are specified as a vector of variable names. Assignments must be made to each of the result variables. However, the calling program is not required to make use of all the g p g qreturn values.
25
Returning multiple results
1 function [area volume] = cylinder2(height radius)1. function [area, volume] = cylinder2(height, radius)2. % function to compute the area and volume 3. % of a cylinder4 % [area ol me] c linder2(height radi s)4. % [area, volume] = cylinder2(height, radius)5. base = pi .* radius.^2;6. volume = base .* height;7 2* i * di * h i ht + 2 * b
• The cylinder2 function with multiple results These results are
7. area = 2* pi * radius .* height + 2 * base;
The cylinder2 function with multiple results. These results are specified as a vector of variable names, each of which must be assigned from the code body.
26
Returning multiple results
Do it yourself
• Adapt the original cylinder2 function and perform the following tests in the command window:
>> [a, b] = cylinder2(1, 1)a =
12.566412.5664b =
3.1416
>> cylinder2(1,1)ans =
12 5664
27
12.5664
Returning multiple results
• Notice that the normal method to access the multipleNotice that the normal method to access the multiple answers is to put the names of the variable to receive the results in a vector. The names may be any legal
i bl d th l t d i thvariable name, and the values are returned in the order of the result defined.
• If you choose less than the full number of results (or y (none at all), the answers that are specified are allocated from left to right from the available results.
28
Important points
• Before you include a function in a complexBefore you include a function in a complex algorithm, you should always test its behavior in isolation in a script. This test script should validate
t l th l ti f th f ti b tnot only the normal operation of the function, but also its response to incorrect input data it might receive.
• Although any legal Matlab instruction is permitted within the code body of a function, it is considered bad form to display values in the command windowbad form to display values in the command window (remember to add the semicolon after each instruction/sentence).
29
Outline of Lab 4
• Objectives of Lab 4
• Concept of user-defined functionsp
• Storing and using functions
Ad d kill R i• Advanced skill: Recursion
30
Recursion
• Recursion is an alternative technique by which a• Recursion is an alternative technique by which a code block can be repeated in a control manner. • In the last lab, we saw repetition achieved by
inserting control statements in the code (either for or while) to determine how many times a code block would be repeated.
• Recursion uses the basic mechanism for invoking functions to manage the repetition of a block of code.
31
Recursion
• A recursive function can be understood as a• A recursive function can be understood as a private helper (call itself) function. A canonical demonstration of recursion is the computation of nfactorial We co ld ie the calc lation of 5! infactorial. We could view the calculation of 5! in the following two ways:
5! = 5 * 4 * 3 * 2 * 15! = 5 * 4!
The second representation shows the idea of recursionrecursion.
32
Recursion
• There are three necessary features of a recursive• There are three necessary features of a recursive function:
1 Th f ti t ll l f it lf1. The function must call a clone of itself;
2. There must be a terminating condition to stop the process;the process;
3. The parameter to that call must move the function toward the terminating condition.
33
General template of recursion
function <result> = <function_name> (<formal_parameters>)<documentation><documentation>
if <terminating condition 1><result> = <initial value 1>
elseif <terminating condition 2>elseif terminating condition 2<result> = <initial value 2>
…else
Th i bl l b l l i bl f
<result> = <operation> (<formal>, <function_name> (<new>))end
• The variable <result> may be any legal variable name or a vector of variable names.
• As usual with functions, you should supply at least one line of <documentation> to define its purpose and implementation
34
<documentation> to define its purpose and implementation.
General template of recursion
function <result> = <function_name> (<formal_parameters>)<documentation><documentation>
if <terminating condition 1><result> = <initial value 1>
elseif <terminating condition 2>elseif terminating condition 2<result> = <initial value 2>
…else
Th fi d i d i i i d i h di i d hi h h
<result> = <operation> (<formal>, <function_name> (<new>))end
• The first design decision is to determine the conditions under which the recursive process should stop, and how to express this as the <terminating condition n> tests.
• Each exit from the function must assign values to all the result variables
35
• Each exit from the function must assign values to all the result variables.
General template of recursion
function <result> = <function_name> (<formal_parameters>)<documentation><documentation>
if <terminating condition 1><result> = <initial value 1>
elseif <terminating condition 2>elseif terminating condition 2<result> = <initial value 2>
…else
<result> = <operation> (<formal>, <function_name> (<new>))end
• The <initial value n> entries are the values of the results at the corresponding terminating conditions.
36
General template of recursion
function <result> = <function_name> (<formal_parameters>)<documentation><documentation>
if <terminating condition 1><result> = <initial value 1>
elseif <terminating condition 2>elseif terminating condition 2<result> = <initial value 2>
…else
Th d d i d i i i d i h i hi h i
<result> = <operation> (<formal>, <function_name> (<new>))end
• The second design decision is to determine the <operation>, which is the specific mathematical or logical operation that must be performed to combine the current parameters with the result of the recursive call to create a new value of the <result>.
37
General template of recursion
function <result> = <function_name> (<formal_parameters>)<documentation><documentation>
if <terminating condition 1><result> = <initial value 1>
elseif <terminating condition 2>elseif terminating condition 2<result> = <initial value 2>
…else
Th l d i d i i i d i h h
<result> = <operation> (<formal>, <function_name> (<new>))end
• The last design decision is to determine how to compute the parameters of the recursive call to ensure that the process move toward at least one of the <terminating condition n> states.
38
Example of N factorial recursion
1. function result = fact(N)2. % recursive computation of N!3. if N == 04. result = 1;
l5. else6. result = N * fact(N-1);7. end
• Line3: shows the terminating condition.• Line4: shows the result at the corresponding terminating condition.• Line6: calls a clone of the function, which moves closer to termination
by reducing N and computing the current result by multiplication.
39
Example of N factorial recursion
Do it yourself:
• Create the fact() function, and run it from the command window with the parameters from 0 to 10.
>> fact(0)ans =
11
>> fact(5)ans =ans
120
40
Another example of recursion
• Fibonacci series:
a1=1, a2=1, a3=2, a4=3, a5=5, a6=8, a7=13, a8=21, a9=34, a10=55,…
an=an-1+an-2.
1. The recursive condition is: fib(N) = fib(N-1) + fib(N-2).2 Th i t i ti diti h N 1 N 2 th i 12. There is a terminating condition: when N=1 or N=2, the answer is 1.3. The solution is moving toward the terminating condition, since as long
as N is a positive integer, computing N-1 and N-2 will move toward 1 or 2or 2.
41
Another example of recursion
1. function result = fib(N)2. % recursive computation of the Nth Fibonacci number3. if N == 1 | | N == 24. result = 1;
l5. else6. result = fib(N-1) + fib(N-2);7. end
Do it yourself:
• Create the fib() function, and run it from the command window with the parameters from 5 to 10.
>> fact(10)ans =
42
ans 55
Summary of Lab 4
1. General concepts of user-defined functions1. General concepts of user defined functions2. How to save and run user-defined functions3. How to return multiple results from one user-
defined function4. Basic principles and rules of recursive
programmingprogramming
43
Next class
• File input and output• File input and output Matlab workspace I/O
High-level I/O functions High level I/O functions
Low-level file I/O
44