november 1, 2005 lecture 12 - by paul lin 1 cpet 190 user defined functions lecture 12 problem...

23
November 1, 2005 November 1, 2005 Lecture 12 - By Paul Lin Lecture 12 - By Paul Lin 1 CPET 190 CPET 190 User Defined Functions User Defined Functions Lecture 12 Lecture 12 Problem Solving with Problem Solving with MATLAB MATLAB http://www.etcs.ipfw.edu/~lin http://www.etcs.ipfw.edu/~lin

Upload: cody-thompson

Post on 11-Jan-2016

217 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 11

CPET 190 CPET 190

User Defined FunctionsUser Defined Functions

Lecture 12Lecture 12Problem Solving with MATLAB Problem Solving with MATLAB

http://www.etcs.ipfw.edu/~linhttp://www.etcs.ipfw.edu/~lin

Page 2: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 22

User-Defined M-File FunctionsUser-Defined M-File Functions

12-1 Intro to MATLAB Functions12-1 Intro to MATLAB Functions

12-2 Variable Passing (By Value)12-2 Variable Passing (By Value)

Page 3: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 33

User-Defined M-File FunctionsUser-Defined M-File Functions

Past 30-years Programming PracticesPast 30-years Programming Practices• ReuseReuse• PortabilityPortability• ReliabilityReliability• MaintainabilityMaintainability

Programming Language and PracticesProgramming Language and Practices• Modular (Structured) Programming (1970 to late Modular (Structured) Programming (1970 to late

1980s) – Fortran, C, Ada; (MATLAB 1990 – present)1980s) – Fortran, C, Ada; (MATLAB 1990 – present)• Object-Oriented Programming (1990s) – SmallTalk, Object-Oriented Programming (1990s) – SmallTalk,

C++, JavaC++, Java• Component-Based Programming (2000s) – C#, Component-Based Programming (2000s) – C#,

or .NETor .NET

Page 4: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 44

User-Defined M-File FunctionsUser-Defined M-File Functions

MATLAB Programming Language Features MATLAB Programming Language Features (Modular and Structured)(Modular and Structured)• Top-down design – Module and subtasksTop-down design – Module and subtasks• Independent testing of function-level sub-tasks - Independent testing of function-level sub-tasks -

maintainabilitymaintainability• Reuse – reusability thorough packaging of functions Reuse – reusability thorough packaging of functions

, reduce programming efforts and increasing , reduce programming efforts and increasing productivityproductivity

• Isolation from unintended side effects – reliability Isolation from unintended side effects – reliability through data hiding, separate workspace for each through data hiding, separate workspace for each function to avoid certain mistakesfunction to avoid certain mistakes

Page 5: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 55

Introduction to MATLAB Introduction to MATLAB FunctionsFunctions

Types of M-File FunctionsTypes of M-File Functions• MATLAB Built-In MATLAB Built-In

Functions: abs(x), cos(x), Functions: abs(x), cos(x), sin(x), max(x)sin(x), max(x)

• User-Defined M-File User-Defined M-File Functions (increase code Functions (increase code re-usability)re-usability)

FunctionsFunctions• Subroutines or Subroutines or

Procedures (providing Procedures (providing services)services)

• Function name, Function name, arguments, return arguments, return arguments list (values)arguments list (values)

• Function CallsFunction Calls

Function M File

Input Data

Output Data

Page 6: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 66

Introduction to MATLAB Introduction to MATLAB FunctionsFunctions

MATLAB Function FormatMATLAB Function Format

functionfunction [out_arg1, out_arg2, …] = [out_arg1, out_arg2, …] = function_name(in_arg1, in_arg2, …)function_name(in_arg1, in_arg2, …)

% Comments lines% Comments lines

% More comments% More comments

Executable codesExecutable codes

(return) (return) -- Optional-- Optional

(end) (end) -- For version 7.0 and newer-- For version 7.0 and newer

Page 7: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 77

MATLAB Built-In FunctionsMATLAB Built-In Functions

Toolbox\matlab\Toolbox\matlab\• elefun folder elefun folder

(elementary functions)(elementary functions)• elemat folder elemat folder

(elementary matrix (elementary matrix function)function)

• general foldergeneral folder• etcetc

Page 8: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 88

MATLAB Built-In FunctionsMATLAB Built-In Functions

\toolbox\matlab\elefun\toolbox\matlab\elefun Elementary Math Elementary Math

FunctionsFunctions• abs.mabs.m• exp.mexp.m• cos.mcos.m• sin.msin.m• pow.mpow.m

Page 9: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 99

MATLAB fliplr FunctionMATLAB fliplr Functionfunction function yy = fliplr(x)= fliplr(x)%FLIPLR Flip matrix in left/right direction.%FLIPLR Flip matrix in left/right direction.% FLIPLR(X) returns X with row preserved and columns flipped% FLIPLR(X) returns X with row preserved and columns flipped% in the left/right direction.% in the left/right direction.% % % X = 1 2 3 becomes 3 2 1% X = 1 2 3 becomes 3 2 1% 4 5 6 6 5 4% 4 5 6 6 5 4%%% See also FLIPUD, ROT90, FLIPDIM.% See also FLIPUD, ROT90, FLIPDIM.

% Copyright 1984-2002 The MathWorks, Inc.% Copyright 1984-2002 The MathWorks, Inc.% $Revision: 5.9 $ $Date: 2002/04/08 20:21:05 $% $Revision: 5.9 $ $Date: 2002/04/08 20:21:05 $

if ndims(x)~=2, error('X must be a 2-D matrix.'); endif ndims(x)~=2, error('X must be a 2-D matrix.'); end[m,n] = size(x);[m,n] = size(x);yy = x(:,n:-1:1); = x(:,n:-1:1);

Return value

Error Checking

An Example

8-line Help Comments

Page 10: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1010

fliplr Functionfliplr FunctionIf x = [1 2 3; 4 5 6]; orIf x = [1 2 3; 4 5 6]; or = = 1 2 31 2 3 4 5 64 5 6[m,n] = size(x)[m,n] = size(x)m= 2, n = 3m= 2, n = 3 y = x(:,n:-1:1);y = x(:,n:-1:1);

x(:, -- All rows remain unchangedx(:, -- All rows remain unchanged n:-1:1 -- Colon operator to access column elementsn:-1:1 -- Colon operator to access column elements

• The meaning of first n is to copy the column-n of the x array, into The meaning of first n is to copy the column-n of the x array, into the column-1 of the y arraythe column-1 of the y array

• The meaning of the :1 is to copy the column 1 of x into the very The meaning of the :1 is to copy the column 1 of x into the very last column of ylast column of y

• The meaning of the :-1 is to copy column n-1 of x into column n-1 The meaning of the :-1 is to copy column n-1 of x into column n-1 of y; then decrement the column by -1 to copy the column n-2 of x of y; then decrement the column by -1 to copy the column n-2 of x into the column-2 of y; until all columns between n and 1 are into the column-2 of y; until all columns between n and 1 are copied.copied.

y = 3 2 1y = 3 2 1 6 5 46 5 4

Page 11: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1111

View fliplr FunctionView fliplr Function

>> dbtype fliplr>> dbtype fliplr1 function y = fliplr(x)1 function y = fliplr(x)2 %FLIPLR Flip matrix in left/right direction.2 %FLIPLR Flip matrix in left/right direction.3 % FLIPLR(X) returns X with row preserved and columns flipped3 % FLIPLR(X) returns X with row preserved and columns flipped4 % in the left/right direction.4 % in the left/right direction.5 % 5 % 6 % X = 1 2 3 becomes 3 2 16 % X = 1 2 3 becomes 3 2 17 % 4 5 6 6 5 47 % 4 5 6 6 5 48 %8 %9 % See also FLIPUD, ROT90, FLIPDIM.9 % See also FLIPUD, ROT90, FLIPDIM.10 10 11 % Copyright 1984-2002 The MathWorks, Inc.11 % Copyright 1984-2002 The MathWorks, Inc.12 % $Revision: 5.9 $ $Date: 2002/04/08 20:21:05 $12 % $Revision: 5.9 $ $Date: 2002/04/08 20:21:05 $13 13 14 if ndims(x)~=2, error('X must be a 2-D matrix.'); end14 if ndims(x)~=2, error('X must be a 2-D matrix.'); end15 [m,n] = size(x);15 [m,n] = size(x);16 y = x(:,n:-1:1);16 y = x(:,n:-1:1);

Page 12: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1212

Example 1 A User-Define Function Example 1 A User-Define Function ExampleExample

Phases of Function DevelopmentPhases of Function Development- Designing phaseDesigning phase- Coding phaseCoding phase- Testing PhaseTesting Phase- Release and ImplementationRelease and Implementation

The Desired FunctionThe Desired Function Calculating the HypotenuseCalculating the Hypotenuse Hypotenuse – the side of a right-Hypotenuse – the side of a right-

triangle that is opposite the right triangle that is opposite the right angle (domain knowledge)angle (domain knowledge)

Function name – hypotenuseFunction name – hypotenuse Input arguments – a, bInput arguments – a, b Output arguments – hOutput arguments – h The function hypotenuse.mThe function hypotenuse.mfunction h = hypotenuse(a, b)function h = hypotenuse(a, b)h = sqrt(a.^2 + b.^2);h = sqrt(a.^2 + b.^2);

A

BC

AC - Hypotenuse

ha

b

Page 13: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1313

Example 1 A User-Define Function Example 1 A User-Define Function ExampleExample

Code the hyotense.m M-file function and save it under Code the hyotense.m M-file function and save it under cpet190/codes foldercpet190/codes folder

Run the function: Click on Debug -> RunRun the function: Click on Debug -> Run

Error message showsError message shows

Page 14: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1414

Example 1 A User-Define Function Example 1 A User-Define Function ExampleExample

Testing Functions:Testing Functions: First Testing: First Testing:

hypotense(3,4)hypotense(3,4) Second Testing:Second Testing:

a = 3, b =4;a = 3, b =4;

hypotenuse(a,b)hypotenuse(a,b) Third Testing:Third Testing:

side_a = 3; side_b = 4;side_a = 3; side_b = 4;

c = hypotenuse(side_a, c = hypotenuse(side_a, side_b)side_b)

Page 15: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1515

Variable Passing (By Value)Variable Passing (By Value)

MATLAB programs communicate with their MATLAB programs communicate with their functions – values passing for both arrays functions – values passing for both arrays and scalarsand scalars

Make a copy of the actual arguments and Make a copy of the actual arguments and passes them to the functionpasses them to the function

Service requesting function cannot modify Service requesting function cannot modify the actual argumentsthe actual arguments

Page 16: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1616

Example 2 Parallel ResistanceExample 2 Parallel Resistance

Function for calculating Parallel Function for calculating Parallel resistanceresistance

Domain Knowledge:Domain Knowledge:Req = R1 || R2 = (R1 * R2)/(R1 + R2)Req = R1 || R2 = (R1 * R2)/(R1 + R2) Function designFunction design function Req = p_rs(r1, r2)function Req = p_rs(r1, r2)% Comments% Comments% % if r1 < 0if r1 < 0 Req = -1;Req = -1;elseif r2 < 0elseif r2 < 0 Req = -1;Req = -1;elseif (r1 == 0) || (r2 == 0)elseif (r1 == 0) || (r2 == 0) Req = 0;Req = 0;else else Req = (r1 * r2)/(r1 + r2)Req = (r1 * r2)/(r1 + r2)end end

R2

R1

RT = xxx Ω

Rn

Page 17: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1717

Example 2 Parallel ResistanceExample 2 Parallel Resistance

CodingCoding DocumentationDocumentation

• PurposesPurposes• Calling sequenceCalling sequence• Defining VariablesDefining Variables• Record of revisionsRecord of revisions

TestingTesting• p_rs(10,10) -- 5 ohmsp_rs(10,10) -- 5 ohms• p_rs(10, p_rs(20,20)) – 5 p_rs(10, p_rs(20,20)) – 5

ohmsohms• p_rs(ra, rb)p_rs(ra, rb)

Page 18: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1818

Example 3 Rectangular-to-Polar Example 3 Rectangular-to-Polar ConversionConversion

Problem StatementProblem Statement• The location of a point The location of a point

in a cartesian plane can in a cartesian plane can be expressed in either be expressed in either the rectangular the rectangular coordinates(x,y) or the coordinates(x,y) or the polar coordinates(r, polar coordinates(r, theta) as shown on the theta) as shown on the slide. slide.

• The point P(x,y) or P(r, The point P(x,y) or P(r, theta)theta)

• Two functions for Two functions for converting between converting between rectangular coordinate rectangular coordinate polar coordinatepolar coordinate

X Axis

Y Axis

P

x

y

r

q

Page 19: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 1919

Example 3 Rectangular-to-Polar Example 3 Rectangular-to-Polar ConversionConversion

Domain KnowledgeDomain Knowledgex = r cos(theta)x = r cos(theta)y= r sin(theta)y= r sin(theta)r = sqrt(x^2 + y^2)r = sqrt(x^2 + y^2)theta = tantheta = tan-1-1(y/x)(y/x) Define the function’s name, inputs and outputsDefine the function’s name, inputs and outputsfunction [x, y] polar2rect(r, theta)function [x, y] polar2rect(r, theta)function [r, theta] rect2polar(x,y)function [r, theta] rect2polar(x,y) Convert equations to MATLAB statementConvert equations to MATLAB statement Code and test functionCode and test function Add documentation to the two functionsAdd documentation to the two functions

Page 20: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 2020

Example 3 Rectangular-to-Polar Example 3 Rectangular-to-Polar ConversionConversion

The two functionsThe two functions

function [x, y] = polar2rect(r, theta)function [x, y] = polar2rect(r, theta)

x = r * cos(theta*pi/180);x = r * cos(theta*pi/180);

y = r * sin(theta*pi/180);y = r * sin(theta*pi/180);

endend

Page 21: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 2121

Example 3 Rectangular-to-Polar Example 3 Rectangular-to-Polar ConversionConversion

The two functionsThe two functions

function [r, theta] = rect2polar(x,y)function [r, theta] = rect2polar(x,y)%ATAN2 Four quadrant inverse tangent.%ATAN2 Four quadrant inverse tangent.% ATAN2(Y,X) is the four quadrant arctangent % ATAN2(Y,X) is the four quadrant arctangent

of the of the % real parts of the elements of X and Y. % real parts of the elements of X and Y. % -pi <= ATAN2(Y,X) <= pi.% -pi <= ATAN2(Y,X) <= pi.r = sqrt(x^2 + y^2);r = sqrt(x^2 + y^2);theta = (180/pi)* atan2(y,x);theta = (180/pi)* atan2(y,x);endend

Page 22: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 2222

Example 3 Rectangular-to-Polar Example 3 Rectangular-to-Polar ConversionConversion

Testing FunctionsTesting Functions

>> [x, y] = polar2rect(5, 36.8699)>> [x, y] = polar2rect(5, 36.8699)x =x = 4.00004.0000y =y = 3.00003.0000

>> [x, y] = polar2rect(5, -36.8699)>> [x, y] = polar2rect(5, -36.8699)x =x = 4.00004.0000y =y = -3.0000-3.0000

Testing FunctionsTesting Functions

>> [r, theta] = rect2polar(4,3)>> [r, theta] = rect2polar(4,3)r =r = 55theta =theta = 36.869936.8699

>> [r, theta] = rect2polar(-4,-3)>> [r, theta] = rect2polar(-4,-3)r =r = 55theta =theta = -143.1301-143.1301

Page 23: November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB lin

November 1, 2005November 1, 2005 Lecture 12 - By Paul LinLecture 12 - By Paul Lin 2323

SummarySummary

Intro to MATLAB FunctionsIntro to MATLAB Functions Variable Passing (By Value)Variable Passing (By Value) Example 1 – Function for Hypotenuse Example 1 – Function for Hypotenuse

calculationcalculation Example 2 – Function for Parallel Example 2 – Function for Parallel

Resistance computationResistance computation Example 3 – Function for rectangular to Example 3 – Function for rectangular to

polar conversionpolar conversion