Topic 6- User Defined Function
Topic 6- User Defined Function
PART 1 - INTRODUCTION
Function Type
Two Types:
1) Built-in function
Functions that come together with the software.
Example of built-in functions;
abs,sin,atand,fix,sgn,mean
Passing
Function call argument
3
Function - Control transfer
Calling a function in script file
Script file
% Get Area of a square find Sides Perimeter
FUNCTIONS SCRIPTS
Functions have their own separate Scripts use the base workspace
workspace
Variables created outside function’s All variables in the global workspace are
workspace are not accessible to other accessible to all scripts
function
Functions communicate with other Script communicate with other scripts
functions using input arguments and by modifying global variables
output arguments (or parameters)
Function should always be used for Scripts are useable for small task but
large program development not appropriate for large programs
Anonymous Function
Creation format & calling
Anonymous function with &without arguments
Saving anonymous function in mat-file
6
Anonymous Function
• Simple one line function
• Does not have to stored in m-file.
• Can be created in Command window or script or
UDF
A way of referring to
the function
Syntax
fnhandlevar = @ (args) functionbody
Arguments correspond to
the arguments that are
passed to the function Valid MATLAB expression
7
Anonymous Function - with arguments
Example
Anonymous
>> circlearea=@(rad) pi*rad.^2; function
>> circlearea(3) Scalar argument
ans =
28.2743
>> area=circlearea(2:4) Vector argument
area =
12.5664 28.2743 50.2655
8
Anonymous Functions - without arguments
Example –
print a random number No argument
9
Anonymous Functions - save in MAT-file
10
Anonymous Functions - save in MAT-file
>> cirarea
cirarea =
@ (radius) pi * radius .^2 11
Anonymous Functions - appending to MAT-file
12
User-Defined Functions
13
5.1: User-Defined Functions (UDF)
• Function is a named section of a program that performs a specific task. MATLAB
allows UDFs written in separate function files.
• A UDF is a MATLAB program that is created by the user, saved as a function file
and then be used like a built-in function.
File_name.m
Variable = function_name(input_argument) Calling
EXAMPLE
calarea.m calarearec.m
function area = calcarea(rad) function area = calcarearec(b,d)
% This function calculates the area % This function calculates the area of
of a circle a rectangle
area = pi* rad * rad area = b * d
end end
printem.m
function printem(a,b)
% This function print two numbers in a sentence format
fprintf(‘The first number is %.1f and the second is %.1f\n’,a,b)
end
>> printem(3.3,2)
The first number is 3.3 and the second is 2.0
Example 2
(Function returning one value)
wave.m
function r = wave(x)
% this function is to generate a sine wave
r = sin(3*x)+sin(3.1*x)
end
>> x = 0:0.1:10
>> y = wave(x)
>> plot(x,y)
Example 3
(Function returning multiple values)
areacirc.m breaktime.m
function [area,circum] = function [hours,minutes, remsecs] =
areacirc(rad) breaktime(totseconds)
% This function calculates % This function breaks a total …
% the area, number of
% and the circumference of % seconds into hours, minutes and …
% the a circle remaining seconds
area = pi*rad * rad hours = floor(totseconds/3600)
circum = 2*pi*rad remsecs = rem(totseconds,3600)
minutes = floor(remsecs/60)
end end
>>[area,circ] = areacir(4)
area = >>[h,m,s] = breaktime(7515)
50.5655 h =
circ = 2
25.1327 m =
5
S =
15
Example 4
B1
H1
B2 H2
H3
B3
Program without function
MInertia1.m
B1 = input ('B1 = ');
B2 = input ('B2 = ');
B3 = input ('B3 = ');
H1 = input ('H1 = '); % …continue
H2 = input ('H2 = ');
H3 = input ('H3 = '); MST1 = MST1 + A1*(Ybar-Y1)^2;
MST2 = MST2 + A2*(Ybar-Y2)^2;
MST1 = (B1*H1^3)/12; MST3 = MST3 + A3*(Ybar-Y3)^2;
MST2 = (B2*H2^3)/12;
MST3 = (B3*H3^3)/12; MSTall = MST1 + MST2 + MST3;
Y1 = H3+H2+H1/2;
Y2 = H3+H2/2;
Y3 = H3/2;
Area = A1 + A2 + A3;
Ybar = (A1*Y1+A2*Y2+A3*Y3)/Area;
Program with function
% …continue
MInertia2.m
B1 = input ('B1 = '); MST1 = calMST(MST1,A1,Ybar,Y1);
B2 = input ('B2 = '); MST2 = calMST(MST2,A2,Ybar,Y2);
B3 = input ('B3 = '); MST3 = calMST(MST3,A3,Ybar,Y3);
H1 = input ('H1 = ');
H2 = input ('H2 = '); MSTall = MST1 + MST2 + MST3;
H3 = input ('H3 = ');
fprintf('Moment inertia = %.2f mm^4\n', ...
MST1 = calMI(B1,H1); MSTall)
MST2 = calMI(B2,H2);
MST3 = calMI(B3,H3); function MI = calMI(B,H)
% This function is to calculate the
A1 = calarea(B1,H1); individual moment inertia
A2 = calarea(B2,H2); MI= (B*H^3)/12
A3 = calarea(B3,H3); end
Y1 = H3+H2+H1/2;
Y2 = H3+H2/2; function area = calarea( B,H )
Y3 = H3/2; %This function is to calculate the area
of a rectangle
Area = A1 + A2 + A3; area = B*H
Ybar = (A1*Y1+A2*Y2+A3*Y3)/Area; end
A1 = B1*H1;
A2 = B2*H2;
A3 = B3*H3;
end
MInertia4.m
B = zeros(1,3);
H = zeros(1,3);
for i = 1:3
B(i) = input(['B' num2str(i) ' = ']);
H(i) = input(['H' num2str(i) ' = ']);
end
MST = (B.*H.^3)/12;
A = B.*H;
Y(1) = H(3)+H(2)+H(1)/2;
Y(2) = H(3)+H(2)/2;
Y(3) = H(3)/2;
Area = sum(A);
Ybar = sum(A.*Y)/Area;
>> fo2ml(1)
1.00 ounces = 29.57 millilitres
TUTORIAL
3. Write a function to implement the following
quadratic:
𝑄 = 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
where a, b & c are the input variables.
Then, use plot to plot the function in the
range from –10 to 10.
User-Defined Functions (UDF)
P
L1
RA L2 RB
Calculatemoment.m
%This script is to calculate the moment at a specified location of a beam
Variables in each workspace are only visible to script/function in the pertinent workspace
Variable scope in MATLAB is divided into :
I. Local variable
• Variables specific to a function workspace are called local
variables. Typically, local variables do not remain in memory from
one function call to the next.
Example:
Sumprod.m >> sumprod
x = 1:5 x=
s = sum(x) 1 2 3 4 5
p = prod(x) s=
15
p=
120
>> whos
The value of variable in
Name Size Bytes Class
base workspace is
p 1x1 8 double
changeable through script
s 1x1 8 double
x 1x5 40 double
Function Workspace
• Function do not use base workspace
• Each function has it own workspace, separate from base workspace
• Variables in function workspace are called local variables
• Once executed, the variables in the function workspace are gone
Example:
localvar.m
function localvar
P = 12;
Fprintf (‘in the function localvar, the value of p is: %f/n’,p)
end
>>localvar
The value of variable
In the function localvar, the value of p is 12
is unchangeable
through script
>>whos
>>
There is no variable in
the base workspace
Global variable
• One way to allow a function access to variables in the caller’s workspace is to declare
them as global variables.
• The declaration must be done in the caller’s workspace and in the function that wants to
access these variables.
Example:
localvar.m
function localvar
global p
fprintf('In localvar the value of p is %d\n',p)
>> global p;
>> p = 50; 50 is assigned to p in base workspace
>> localvar
In localvar the value of p is 50
The primary difference between nested functions and other types of functions is
that they can access and modify variables that are defined in their parent
functions. As a result:
• Nested functions can use variables that are not explicitly passed as input
arguments.
• In a parent function, you can create a handle to a nested function that contains
the data necessary to run the nested function.
function parent
Parent
disp(‘this is a nested function’)
function
nestedfx
function nestedfx
disp(‘This is the nested function’) Nested
end function
end
Sharing Variable in Nested Function
• As seen earlier, variables in one function workspace are not available to
other functions. However, nested functions can access and modify
variables in the workspaces of the functions that contain them.
• This means that both a nested function and a function that contains it can modify
the same variable without passing that variable as an argument.
Example:
function main1 function main2 function main
x = 5; nestfun2 nestedfun1
nestfun1 Nestedfun2
function nestfun2 end
function nestfun1 x = 5;
x = x + 1; end function nestedfun1
end x = 1;
x = x +1 end
end end
function nestedfun2
X cannot be shared x = 2;
X can be shared through
out the function through out the function end
X cannot be shared through out the
function
f:
Example…(cont.)..:
function parentfun
Functions that return output arguments have
x = 5;
variables for the outputs in their workspace.
nestfun;
However, parent functions only have variables
for the output of nested functions if they explicitly
function y = nestfun
request them. For example, this function
y = x + 1;
parentfun does not have variable y in its
end
workspace:
end
function parentfun
x = 5;
nestfun;
If you modify the code as z = nestfun
follows, variable z is in the
workspace of parentfun: function y = nestfun
y = x + 1;
end
end
Example 6
calculatemoment.m function calRARBmoment(span,span1,load,M_dist
%This is the primary function
clc calrarb
[L,L1,P,M_dist]=inpparam;
calRARBmoment(L,L1,P,M_dist); function calrarb
RA = load*(span1)/span;
RB = load-RA;
fprintf ('RA = %.2fKn and RB = %.2fKn\n',RA,RB)
calmoment(RA)
end
function calmoment(RA)
if (M_dist<span1)
M = RA*M_dist;
function [L,L1,P,M_dist] = inpparam else
% This function is to collect the input variables M = RA*M_dist-P*(M_dist-span1);
disp('when prompted please enter the appropriate end
value') displaymoment(M_dist,M);
L = input ('Please enter the span : '); end
L1 = input('Please enter the first distance : '); end
P = input ('Please enter the load intensity : ');
M_dist = input ('Please enter the distance of the
moment point : ');
Output
>>calculatemoment
when prompted please enter the
appropriate value
Please enter the span : 10
Please enter the first distance : 5
Please enter the load intensity : 10
Please enter the distance of the
moment point : 5
RA = 20.00Kn and RB = -10.00Kn
The moment at 5.00m is 100.00Kn
Example 7
H1 H2
B2
% Centroid of Rect section with a hole function [ Area ] = calarea( width,heigth)
using scalar calculation % this function is to calculate the area
Area = width*heigth;
clear;clc end
b1=input('b1(mm) = ');
h1=input('h1(mm) = ');
b2=input('b2(mm)= ');
h2=input('h2(mm) = ');
function [transd1,transd2,ybar] = caltransD(a1,y1,a2,y2)
%calculate y's %This is the parent function to calculate Ybar and transfer
y1=h1/2; distances
y2=(h1+h2)/2; calybar;