• 검색 결과가 없습니다.

User-Defined Functions

N/A
N/A
Protected

Academic year: 2021

Share "User-Defined Functions"

Copied!
19
0
0

로드 중.... (전체 텍스트 보기)

전체 글

(1)

User-Defined Functions

MATLAB has a special mechanism designed to make sub-tasks easy to develop and debug independently before building the final program.

It is possible to code each sub-task as a separate function, and each function can be tested and debugged independently of all of the other sub-tasks in the program.

The Benefits of using function includes:

1. Independent testing of sub-tasks

The sub-task can be tested separately to ensure that it performs properly by itself before combining it into the larger program

2. Reusable code

It reduces the total programming effort required 3. Isolation from unintended side effects

Each function has its own work-space with its own variables, independent of all other functions and of the calling program

(2)

Introduction to MATLAB Functions

Script files are just collections of MATLAB statements that are stored in a file with m extent.

When a script file is executed, the result is same as it would be if all of the commands had been typed directly into the Command Window.

Script files share the Command Window’s workspace.

Any variables that were defined before the script file starts are visible to the script file

 Any variables created by the script file remain in the workspace after the script file finishes executing.

A script file has no input arguments and returns no results, but script can communicate with other script files through the data left behind in the

workspace.

(3)

MATLAB Functions (Cont….)

A MATLAB Function is a special type of M-file that runs in its own independent workspace

It receives input data through an input argument list and returns results to the caller through an output argument list

The general form of a MATLAB function is

function [out1, out2, …] = myfun (in1, in2, in3, …)

%H1 comment line

%Other comment line ( Executable code) end % function

The first line should start with the word function, followed by output argument list in brackets [out1, out2, …] , = sign, function name (myfun), and input argument list in parentheses (in1, in2, in3, …).

Each MATLAB function should be placed in a file with the same name as the function name, and the file extent .m (myfun.m)

(4)

A function is invoked by naming it in an expression together with a list of actual arguments. This can be done

 By typing function name in the command window

 By including it in a script file or another function

Example 1: Function that implements the quadratic formula

2 0

1 2 4

2 2 2 4

2 ax bx c

b b ac

x a

b b ac

x a

  

  

  

(5)

function [x1,x2]=quadform(a,b,c)

% Calculate the roots d=sqrt(b^2-4*a*c);

x1=(-b+d)/(2*a);

x2=(-b-d)/(2*a);

end % quadform()

Executing from the command window

>>[r1 r2]=quadform(1,-2,1)

Executing using script file

Edit and save script file ‘test.m’

a = 1;

b = -2;

c = 1;

[r1 r2]=quadform(a,b,c)

Calling Program

(6)

Subfunctions and Nested functions

A single M-file can contain code for more than one function

Two other types of functions can be in the same file, subfunctions and nested functions

Subfunctions

A subfunction is mostly a convenient way to avoid unnecessary files

The function at the top of the file is the primary function

Additional functions within the file are called subfunctions and these are only visible to primary functions or to other subfunctions in the same file

They have private workspaces and otherwise behave like functions in separate files

Only the primary function, not the subfunctions can be called from sources outside the file

(7)

sdim

sarea

svol File: sdim.m

The Primary function:

Accessible from outside the file

The sub functions: Accessible from inside the file

Subfunctions

(8)

Example: Example for using subfunctions

function [x1, x2] = quadform (a,b,c) % Primary function d= discrim (a, b, c);

x1=(-b+d)/(2*a);

x2=(-b-d)/(2*a);

end % quadform ()

function d = discrim (a, b, c) % subfunction d= sqrt (b^2-4*a*c);

end % discrim ()

(9)

Nested functions

host_ function

nested_function_1

end % nested_function_1 nested_function_2

end % nested_function_2

end % host_function

Variables defined in the host function are visible inside any nested functions

Variables defined within nested functions are not visible in the host function.

nested_function-2 can be called from within host_function or nested_function _1.

nested_function-1 can be called from within host_function or nested_function _2.

(10)

Nested Functions

Nested functions behave little differently

They are defined within the scope of the another function

Tthey share access to the containing function’s workspace

(11)

Example: Example for using nested functions

function [x1, x2] = quadform (a,b,c) % host_ function function discrim % nested function

d= sqrt (b^2-4*a*c);

end % discrim () discrim;

x1=(-b+d)/(2*a);

x2=(-b-d)/(2*a);

end % quadform ()

(12)

Example: Example for using subfunctions

function [area, vol] = sdim (r) % Primary function

% sdim find area and volume of a sphere.

area = sarea(r);

vol = svol(r);

end % function sdim

function a = sarea(r) % Subfunction

% Calculate area a = 4*pi*r^2;

End % function a

function v = svol(r) % Subfunction

% Calculate volume.

V=(4/3)*pi*r^3;

end

(13)

Anonymous Functions

Annonymous functions can capture variables used in their definition but not passed as arguments

Examples:

sincos= @(x) sin(x)+cos(x);

w = @(x, t, c) cos (x-c *t)

(14)

Function functions

A function function takes one or more functions as inputs

Examples:

>> f = @(x) sin(x);

>> fzero (f, 3) ans =

3.1416

We can also pass in sin function directly

>> fzero (@sin, 3)

(15)

PRACTICE SESSION 2 1. How would you tell MATLAB to display

(i) exponential format with 15 significant digits (ii) 5 digits plus exponent

(iii) 5 total digits with or without exponent (iv) four digits after decimal

(v) 15 total digits with or without exponent

2. What do the following sets of statements do? What is the output from them?

(a) radius = input (‘Enter circle radius: \n’);

area = pi * radius^2;

str = [‘The area is’ num2str (area)];

disp (str);

(b) value = int2str(pi);

disp ([‘The value is ‘ value ‘!’])

(16)

3. What do the following sets of statements do? What is the output from them?

value = 123.4567e2;

fprintf (‘value = %e \n’, value);

fprintf (‘value = %f \n’, value);

fprintf (‘value = %g \n’, value);

fprintf (‘value = %12.4f \n’, value);

(17)

4. Examine the following MATLAB statements. Are they correct or incorrect? If they are correct, what do they output? If they are

incorrect, what is wrong with them?

color = ‘yellow’;

switch (color) case (‘red’),

disp (‘Stop now!’);

case (‘yellow’),

disp (‘Prepare to stop.’);

case (‘green’), disp (‘Proceed’);

otherwise’

disp (‘Illegal color encountered’);

end

(18)

5. Determine whether the following function call is correct or not? If it is incorrect, specify what is wrong with them?

out= test1(6);

function res = test1(x,y) res=sqrt(x^2+y^2);

end % function test1

(19)

6. The distance between two points (x1, y1) and (x2, y2) on a Cartesian coordinate plane is given by the equation

Write a function dist to calculate the distance between two points (x1, y1) and (x2, y2) specified by the user. Use the program to calculate the distance

between the points (2, 3) and (8, -5)

(i) From the command window (ii) Using a script file testdist

)2 1 ( 2

)2 1

(x2 x y y

d

참조

관련 문서

„ Process rank (in range 0, 1, …, p-1) returned through second argument.

The melanoma cell line WM793 was employed for the Fascin and MST2 knock-down and then analyzed by the Western blot assay, and the melanoma xenograft followed by Fascin

Model performances in the stations of Nam river monitoring data 42 Table 15... List

LIST OF TABLES... LIST

– A system or plant equipment list or P&ID, knowledge of equipment function and failure modes, knowledge of system or plant function and response to equipment

: At a critical point an infinitesimal variation of the independent variable results in no change in the value of the function..

The result of this study on the intervention of function words in children with language development delay shows that intervention of function words by grammatically

At first, I arranged the current conditions and function of container terminal in the port of Busan through the existing literature study on the function