• 沒有找到結果。

# >> Lecture 3 2

N/A
N/A
Protected

Share ">> Lecture 3 2"

Copied!
40
0
0

(1)

1 >> Lecture 3

2 >>

3 >> -- Functions

4 >>

Zheng-Liang Lu 165 / 204

(2)

### Functions

A functionis a piece of computer code that accepts aninput argument from the user and providesoutput to the program.

Functions allow you tomodularizea program by separating its tasks into self-containedunits.

We can program more efficientlyandavoid rewriting the computer code for calculations that are performed frequently.

There are plenty of built-in functions provided by MATLAB.

Note that most of them can be implemented by yourself.

Write down the algorithm first, and then program it.

Zheng-Liang Lu 166 / 204

(3)

### Built-in Arithmetic Functions

Zheng-Liang Lu 167 / 204

(4)

### Built-in Rounding Functions

Zheng-Liang Lu 168 / 204

(5)

### Built-in Discrete Math Functions

Zheng-Liang Lu 169 / 204

(6)

### Built-in Max Functions

Zheng-Liang Lu 170 / 204

(7)

### Built-in Max Functions (Cont’d)

There are also min functions to find the minimal elements in arrays, similar to max.

Zheng-Liang Lu 171 / 204

(8)

### Built-in Average Functions

Zheng-Liang Lu 172 / 204

(9)

### Built-in Size Functions

Zheng-Liang Lu 173 / 204

(10)

### Variance and Standard Deviation

Zheng-Liang Lu 174 / 204

(11)

### Random Number Generators

rand is used to produce a test data for your program.

rand is also widely used in Monte Carlo simulation and random number generation algorithms of other distributions.1

1See computational statistics.

Zheng-Liang Lu 175 / 204

(12)

### User-Defined Functions

The syntax of a user-defined function is given by

1 function [output var]=function name(input var)

2 % comment section

The output variables, if there exist, are enclosed in square brackets.

The input variables, if there exist, must be enclosed with parentheses.

function name should start with a letter, and be thesameas the file name in which it is saved.

Before this function can be used, it must be saved into the current folder2.

2If not, change the current folder or add the path.

Zheng-Liang Lu 176 / 204

(13)

### Functions without Input and Output

1 function []=star( ) % [] and () can be dropped.

2 theta=pi/2:0.8*pi:4.8*pi;

3 r=ones(1,6);

4 polar(theta,r) % plot in polar coordinate

0.2 0.4

0.6 0.8 1

30

210

60

240 90

270 120

300 150

330

180 0

Zheng-Liang Lu 177 / 204

(14)

### Example: Addition of Two Numbers

2 % input: x,y (two numbers)

3 % output: z (sum of x and y)

4 z=x+y;

Zheng-Liang Lu 178 / 204

(15)

### Example: Mean of A Sequence

1 function y=myMean(x)

2 % input: x (array)

3 % output: y (mean)

4

5 sum=0;

6 for i=1:length(x)

8 end

9 y=sum/length(x);

Zheng-Liang Lu 179 / 204

(16)

### Numbers of Arguments

nargin determines the number of input arguments in a function when executed.

nargout determines the number of output arguments from a function when executed.

varargin is a special word with two roles:

varargin declares a function withany numberof arguments.3 The variable varargin itself is acell arraycontaining the optional arguments to the function.

varargout is a special word similar to varargin but for outputs.

3Note that varargin must be declared as the last input argument and collects all the inputs from that point onwards.

Zheng-Liang Lu 180 / 204

(17)

### Example

2 switch nargin

3 case 0

4 disp('No input.')

5 case 1

6 x = varargin{1};

7 z = x;

8 case 2

9 x = varargin{1};

10 y = varargin{2};

11 z = x + y;

12 case 3

13 x = varargin{1};

14 y = varargin{2};

15 w = varargin{3};

16 z = x + y + w;

Zheng-Liang Lu 181 / 204

(18)

17 otherwise

18 error('\nToo many inputs.\n');

19 end

20 end

nargin, nargout, varargin and varargout provide a flexible design for user-defined functions.

Note that the key word varargin and varargout should be the last item in the list.

Zheng-Liang Lu 182 / 204

(19)

### Scope of Variables

The variables used in function m files are known as local variables.

Any variable defined within the function exists only for the function to use.

The only way a function can communicatebetween other functions is through input arguments and the outputs it returns.

Unlike local variables,global variables are available to all parts of a computer program.

Useglobalx to declare x as a global variable.

In general, it is a bad idea to define global variables.4

4Recall the modularity.

Zheng-Liang Lu 183 / 204

(20)

### Example: Local Variables

1 function test

2 x=0;

3 fprintf('%d\n',x);

4 loop(x,5);

5 fprintf('%d\n',x);

6 end

7

8 function loop(x,n)

9 for i=1:n

10 x=x+1;

11 fprintf('%d\n',x);

12 end

13 end

What are the numbers shown?

How to returnx in loop to test?

Zheng-Liang Lu 184 / 204

(21)

### Example: Global Variable

1 function test1(x)

2 global g

3 g=g+x;

4 disp(g)

5 test2(g)

6 end

7

8 function test2(y)

9 global g

10 g=g+y;

11 disp(g)

12 end

Zheng-Liang Lu 185 / 204

(22)

1 clear all

2 clc

3 % main

4 global g

5 g=0;

6 disp(g)

7 test1(1);

1 >>

2 0

3

4 1

5

6 2

What if you take globalout of the function?

Zheng-Liang Lu 186 / 204

(23)

### Types of User-Defined Functions

Primary functions andsubfunctions Anonymous functions

Nested functions Private functions

Zheng-Liang Lu 187 / 204

(24)

### Primary Functions and Subfunctions

A function m-file may containmore than one user-defined function.

The first defined function in the file is called the primary function, whose name is the same as the m-file name. All other functions in the file are called subfunctions.

Subfunctions are normally visible onlyto the primary function and other subfunctions in the same file.

Note that the order of the subfunctions does not matter, but function names must beunique within the m-file.

Zheng-Liang Lu 188 / 204

(25)

### Example

1 function [a c] = circle(r) % primary function

2 a = area(r);

3 c = circumference(r);

4 end

5

6 function y=area(x) % subfunction 1

7 y = pi*x.ˆ2;

8 end

9

10 function v=circumference(u) % subfunction 2

11 v = 2*pi*u;

12 end

Zheng-Liang Lu 189 / 204

(26)

1 >> [a c] = circle(2)

2

3 a =

4

5 12.5664

6 7

8 c =

9

10 12.5664

Note that if only one variable is assigned as output of the function, say, circle, then the area is returned while the circumference is dropped.

Zheng-Liang Lu 190 / 204

(27)

### Example

5

One subfunction can be called by other subfunctions in addition to the primary function.

1 function test1

2 fprintf('Hi, there. This is test1.\n');

3 test2;

4 end

5

6 function test2

7 fprintf('Hi, there. This is test2.\n');

8 test1;

9 end

Notice that two subfunctions calling each other can lead to a loop, resulting a fatal crash.

5Thanks to a lively class discussion (MATLAB-238) on June 14, 2014.

Zheng-Liang Lu 191 / 204

(28)

### Anonymous Functions

Anonymous functions enable you to create a simple function without needing to create an m-file for it.

Anonymous functions are defined by thefunction handle, denoted by @, in the command window or in an m-file, and are available only until the workspace is cleared.

For example,

1 >> f=@(x) x.ˆ2+x+1 % x.ˆ2 allows vectorization.

2 >> f([1 10])

3

4 ans =

5

6 3 111

Zheng-Liang Lu 192 / 204

(29)

You can passthe handle of an anonymous function to other functions. (Try.)

You can create anonymous functions having more thanone input.

One anonymous function can call another to implement function composition.

1 >> f = @(x,y) sqrt(x.ˆ2+y.ˆ2); % f is a function ...

handle

2 >> g = @(x,y) f(x,y).ˆ2; % g is a composite function

3 >> g(3,4)

4

5 ans =

6

7 25

Zheng-Liang Lu 193 / 204

(30)

### Nested Functions

Functions are said to benestedif the functions are defined within the parent function.

A nested function can access the variables of its parent function.

1 function f = parabola(a,b,c)

2 f = @p; %f is a function handle of p

3 function y = p(x) % p shares a, b, and c

4 y = a*x.ˆ2 + b*x + c;

5 end

6 end

Zheng-Liang Lu 194 / 204

(31)

1 >> y = parabola(1, 2, 1); % that is y=xˆ2+2*x+1

2 >> y(5)

3

4 ans =

5

6 36

Note that the function parabolareturns a function.

Also, the nested functions are defined anywherewithin the main function. (Why?)

Zheng-Liang Lu 195 / 204

(32)

67

### : Without Nested Functions?

1 function y = p(a, b, c)

2 y = @(x) a * x .ˆ 2 + b * x + c;

3 end

6Thanks to a lively class discussion (MATLAB-244) on August 22, 2014.

7Contribution by Ms. Queenie Chang (MAT25108) on March 18, 2015.

Zheng-Liang Lu 196 / 204

(33)

### Private Functions

Private functions are useful when you want to limit the scope of a function.

A private functions resides in subfolder with the special name private.

The private function is visible onlyto functions in the parent directory.

Note that youcannot call the private function from the command line or from functions outside the parent of the private folder.

Zheng-Liang Lu 197 / 204

(34)

### Precedence When Calling Functions

We can conduct the following experiment for this:

1 clear; clc;

2 % main

3 n = 10;

4 x = rand(1, n);

5 mu = mean(x);

6 sigma = std(x, mu);

1 function y = mean(x)

2 fprintf('This is my mean.\n');

3 y = sum(x) / length(x)

4 std(x,y); % invoking std function

5 function z = std(x,y)

Zheng-Liang Lu 198 / 204

(35)

6 fprintf('This is my 1st std (nested ...

function).\n');

7 z = sqrt(sum(x .ˆ 2) / length(x) - y ˆ 2)

8 end

9 end

10

11 function z = std(x, y)

12 fprintf('This is my 2nd std (subfunction).\n');

13 z = sqrt(sum(x .ˆ 2) / length(x) - y ˆ 2)

14 end

1 function z = std(x, y)

2 fprintf('This is my 3rd std (local file).\n');

3 z = sqrt(sum(x .ˆ 2) / length(x) - y ˆ 2)

4 end

Zheng-Liang Lu 199 / 204

(36)

1 function z = std(x,y)

2 fprintf('This is my 4th std (private).\n');

3 z = sqrt(sum(x .ˆ 2) / length(x) - y ˆ 2)

4 end

Zheng-Liang Lu 200 / 204

(37)

### Precedence When Calling Functions (Concluded)

1 Nested functions

2 Subfunctions within the same file

3 Private functions

4 Local functions in the same directory

5 Built-in functions

6 Standard m files in PATH

Zheng-Liang Lu 201 / 204

(38)

### Calling Functions

There are four common ways to invoke a function.

As a character string identifying the appropriate function m-file.

1 function y = fun1(x)

2 y = x .ˆ2 - 4; % vectorized function

3 end

1 >> fun1([1 2 3])

2

3 ans =

4

5 -3 0 5

As a function handle to an existing function M-file.

Zheng-Liang Lu 202 / 204

(39)

1 >> feval(@fun1, 3) % returns the function value ...

at 3

2

3 ans =

4

5 5

As a string expression.

1 >> fun2 = 'x .ˆ 2 - 4';

2 >> x = fzero(fun2, [0, 3]); % find the root of ...

fun1 in [0,3]

3

4 x =

5

6 2

Zheng-Liang Lu 203 / 204

(40)

As an inline function object.

1 >> fun inline = inline(fun2);

2 >> x = fzero(fun inline, [0, 3])

3

4 x =

5

6 2

The function handle method (method 2) is the fastest method, followed by method 1.

In addition to speed improvement, another advantage of using a function handle is thatit provides access to subfunctions, which are normally not visible outside of their m-file.

Zheng-Liang Lu 204 / 204

It is not possible to conclude, by an analogous argument, that h is differentiable, since X −1 is defined in an open subset of S, and we do not yet know what is meant by

– It is not hard to show that calculating Euler’s phi function a is “harder than” breaking the RSAa. – Factorization is “harder than” calculating Euler’s phi function

The ProxyFactory class provides the addAdvice() method that you saw in Listing 5-3 for cases where you want advice to apply to the invocation of all methods in a class, not just

– Each time a file is opened, the content of the directory entry of the file is moved into the table.. • File Handle (file descriptor, file control block): an index into the table

It takes 20 cm of ribbon to make a bowknot which is 0.05 m less than a corsage?. Mary has a ribbon of 8

The aim of the competition is to offer students a platform to express creatively through writing poetry in English. It also provides schools with a channel to

An information literate person is able to recognise that information processing skills and freedom of information access are pivotal to sustaining the development of a

Then, it is easy to see that there are 9 problems for which the iterative numbers of the algorithm using ψ α,θ,p in the case of θ = 1 and p = 3 are less than the one of the

By correcting for the speed of individual test takers, it is possible to reveal systematic differences between the items in a test, which were modeled by item discrimination and

double-slit experiment is a phenomenon which is impossible, absolutely impossible to explain in any classical way, and.. which has in it the heart of quantum mechanics -

It is useful to augment the description of devices and services with annotations that are not captured in the UPnP Template Language. To a lesser extent, there is value in

+ normally created for children who are learning phonics + levelled according to the phonics programme it is.

• One of the main problems of using pre-trained word embeddings is that they are unable to deal with out-of- vocabulary (OOV) words, i.e.. words that have not been seen

private methods effectively not inherited be- cause not “visible” to the subclass.. More on Access Permissions:

The remaining positions contain //the rest of the original array elements //the rest of the original array elements.

effective price of choice in training: (wishfully) growth function m H (N) with a break point Lecture 6: Theory of Generalization. Restriction of

– It is not hard to show that calculating Euler’s phi function a is “harder than” breaking the RSA. – Factorization is “harder than” calculating Euler’s phi function (see

– It is not hard to show that calculating Euler’s phi function a is “harder than” breaking the RSA. – Factorization is “harder than” calculating Euler’s phi function (see

When renaming a file without changing file systems, the actual contents of the file need not be movedall that needs to be done is to add a new directory entry that points to

Empirical analysis results show that：in term of the willingness-to-pay, the consumers who are using the IMVS wish to reduce their monthly expenditure, in which those who

Since visible light is not capable of detecting interior defects of a solar cell; it is not easy to reveal invisible micro cracks.. At present it is most common to detect

In this thesis, a periodic hierarchical sliding mode control (PHSMC) is proposed to solve the spherical wheel which is at the constant speed or is still but not in correct

In addition to the construction of Lemma 3.4.1, there is a quite orthogonal way of constructing a pushdown automaton that accepts the language generated by a given