User Defined Functions Spring EE 201
Class Learning Objectives Achieve Comprehension LOL of User Defined Functions. Spring 20122
User Defined Functions -The first line in a function file must begin with a function definition line that has a list of inputs and outputs. -This line distinguishes a function M-file from a script M-file. It’s syntax is as follows: function [output variables]= name(input variables) 3 Spring 2012
function [output variables]= name(input variables) Note that the output variables are enclosed in square brackets [ ], while the input variables must be enclosed with parentheses ( ). The function name ( name) should be the same as the file name in which it is saved (with the.m extension). 4 Spring 2012
Writing User Defined Functions You should write this command at the beginning of the m-file and you should save the m-file with a file name same as the function name 5 Spring 2012
Example: 6 Spring 2012
Note :Brackets [ ] are optional for one output 7 Spring 2012
Example Only the order of the arguments is important, not the names of the arguments: 8 Spring 2012
You can use arrays as input arguments: 9 Spring 2012
Examples of Function Definition Lines 1.One input, one output: function [area_square] = square(side) 2. Brackets are optional for one input, one output: function area_square = square(side) 3. Three inputs, one output: function [volume_box] =box(height,width,length) 10 Spring 2012
Examples of Function Definition Lines 4. One Input, two outputs: function [area_circle,circumf]=circle(radius) 5. No Input, No output: 11 Spring 2012
Example Write a MATLAB program that computes area and circumference of a circle 12 Spring 2012
Area = π (radius) 2 Circumference =2π radius 13 Spring 2012
Solution 14 Spring 2012
Example a) ِ Create a MATLAB user defined function that computes area and circumference of a circle. b) Write a MATLAB program that: -prompt the user to enter the radius in meter. - it computes area and circumference using the function you defined in part (a) 15 Spring 2012
16 Spring 2012
17 Local variables
The variables x and y are local to the function S, so unless you pass their values by naming them x and y, their values will not be available in the workspace outside the function. The variable u is also local to the function. For example: 18 Spring 2012
19 Spring 2012
Example : N >> a=20; >>b=5; v=L(a) v= 22 >>a a= 20 >>b b= 5 N function v=L(a) b=2; v=a+b ; end 20 Spring 2012
Example : N >> x=20; >>b=5; z=L(x) z= 22 >>x x= 20 >>b b= 5 >> a ??? Undefined function or variable 'a'. N function v=L(a) b=2; v=a+b ; end 21 Spring 2012