[go: up one dir, main page]

0% found this document useful (0 votes)
2 views49 pages

Topic 6- User Defined Function

The document provides an overview of User-Defined Functions (UDF) in MATLAB, explaining the differences between built-in functions and UDFs, as well as the structure and benefits of creating UDFs. It covers various types of functions, including anonymous functions, and illustrates how to create and call functions with examples. Additionally, it discusses modular programming, emphasizing the advantages of breaking down solutions into independent modules for easier testing and debugging.

Uploaded by

MohdHilmyNaim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views49 pages

Topic 6- User Defined Function

The document provides an overview of User-Defined Functions (UDF) in MATLAB, explaining the differences between built-in functions and UDFs, as well as the structure and benefits of creating UDFs. It covers various types of functions, including anonymous functions, and illustrates how to create and call functions with examples. Additionally, it discusses modular programming, emphasizing the advantages of breaking down solutions into independent modules for easier testing and debugging.

Uploaded by

MohdHilmyNaim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

User-Defined Functions (UDF)

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

2) User defined function (UDF)


New functions that the programmer defines,
and then uses (call) in either the Command
window or script.
UDF is saved as .m-file.
2
Function - Call and Argument
• A function is implicitly called when an expression that
contains the name of the function is evaluated.
• The passed argument is processed in the function
routine and return none or a single or several values.
• After a function has finished execution, execution
resumes at the point just after the call.

Passing
Function call argument

sqrt(20) Returns 4.4721

3
Function - Control transfer
Calling a function in script file
Script file
% Get Area of a square find Sides Perimeter

area=input('Area of square :');


side=sqrt(area);
perimeter=4*side;
fprintf ('For a square area of %5.1f\n', area)
fprintf ('the side is %4.2f and perimeter is
%4.2f\n', side,perimeter)

Matlab function routine


4
Matlab function vs script

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

>> prtran = @ () fprintf('%.2f\n',rand);


>> prtran() No argument in
call function
0.76

Typing the function handle will display the function definition.


>> prtran No parentheses
prtran =
@ () fprintf('%.2f\n',rand)

9
Anonymous Functions - save in MAT-file

• Frequently used anonymous functions can be saved


in a MAT-file and then loaded from this MAT-file in
every MATLAB Command window.
• Other anonymous function could be appended to the
MAT-file.

10
Anonymous Functions - save in MAT-file

>> cirarea = @ (radius) pi * radius .^ 2;


>> save anonfns cirarea
Saving cirarea function in
>> clear anonfns mat-file
>> load anonfns
>> who

Your variables are:

Cirarea Only one function in anonfns mat-file

>> cirarea
cirarea =
@ (radius) pi * radius .^2 11
Anonymous Functions - appending to MAT-file

>> circircumf =@ (rad) 2 *pi .*rad;


>> save anonfns circircumf -append
>> clear
Appending
>> load anonfns anonymous function
>> who (circircumf) to
existing mat-file
(anonfns)
Your variables are:

Now there two functions


cirarea circircumf in anonfns mat-file

12
User-Defined Functions

Creation format & calling


Anonymous function with &without arguments
Saving anonymous function in mat-file

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.

• Generally, a function involved input arguments (or parameters) and output


variables (or parameters) that can be scalars, vectors or matrices of any size.

• Calculation is performed in the function employing the input parameters, the


results are transferred out using output parameters.

• A Function can be written in MATLAB EDITOR.

• Users can determine:


i) The number of input parameters
ii) The number of output parameters
iii) The name of the function
Benefit of User Defined Function
• The complexity of the entire program can be divided into simple subtask making
the program easier to write, understand and debug.
• Eliminate duplicate code and allow sharing by other program.
• Reducing the size of program
• Facilitate reusability

Type of User Defined Function

• Function without returning value


• Function return one value
• Function return multiple values
Format of writing and calling a function
Function_name.m
function output_argument = function_name(input_argument)
% Summary of this function goes here
% Detailed explanation goes here Writing
end

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

>>Areaofcircle = calcarea(2); >>Areaofrec = calcarearec(2,4);


Areaofcircle = 12.57 OUTPUT Areaofrec = 8 OUTPUT
Example 1
(Function without returning values)

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

Write a program to calculate the moment of inertia of an I-section

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;

A1 = B1*H1; fprintf('Moment inertia = %.2f mm^4\n', ...


A2 = B2*H2; MSTall)
A3 = B3*H3;

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

function MIf = calMST(MST,A,Ybar,Y)


MIf = MST+A*(Ybar-Y)^2
end
Program with function (multiple values)
% …continue
MInertia3.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,MST2,MST3,A1,A2,A3] = ... MSTall)
calMSTnA(B1,B2,B3,H1,H2,H3);
function [MST1,MST2,MST3,A1,A2,A3] = ...
Y1 = H3+H2+H1/2; calMSTnA(B1,B2,B3,H1,H2,H3)
Y2 = H3+H2/2; % This function is to calculate the
Y3 = H3/2; %individual area & moment inertia
MST1 = (B1*H1^3)/12;
Area = A1 + A2 + A3; MST2 = (B2*H2^3)/12;
Ybar = (A1*Y1+A2*Y2+A3*Y3)/Area; MST3 = (B3*H3^3)/12;

A1 = B1*H1;
A2 = B2*H2;
A3 = B3*H3;
end

function MIf = calMST(MST,A,Ybar,Y)


MIf = MST+A*(Ybar-Y)^2
end
Program with function (vectorised)

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;

MST = MST + A.*(Ybar-Y).^2;


MSTall = sum(MST);

fprintf('Moment inertia = %.2f mm^4\n', ...


MSTall)
TUTORIAL
1. The hyperbolic sine for an argument x is
defined as:
𝑓 𝑥 = 𝑒 𝑥 − 𝑒 −𝑥 2
Write an anonymous function to implement
this. Compare yours with the built-in
function sinh.
TUTORIAL
2. Write an anonymous function to convert
from fluid ounces to millilitres. The
conversion is one fluid ounce is equivalent to
29.57 millilitres. The output for the
anonymous function is such that:

>> 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)

PART 2 - MODULAR PROGRAM


5.2: Modular program
• In modular program, the solution is broken down into modules.
• Each is implemented as a function. The benefits are as below:

i) Independent testing of subtasks


• Each subtask can be written as an independent unit. Each subtask
can be tested properly to ensure it performs properly.
• Eliminates the major source of problem before the final program is
even built.

ii) Reusable Code


• The same basic subtask is needed in many parts of a program.
• Reduce the total programming effort and simplify debugging

iii) Isolation from Unintended Side Effects.


• Accidental mistake in programming can only effect the variable
within the function in which the mistake occurred.
5.2.1: Sub-function

• So far, functions are written in separate M-files.


• However, it is possible to have more than one function in a given
M-file.
• If one function calls another function, the first function is the
primary function and the called function is sub-function
• The name of the M-file would be the same as the name of the
primary function.
Example 5
Create a program to calculate the reactions of the beam system below
and the moment at the specified point

P
L1

RA L2 RB
Calculatemoment.m
%This script is to calculate the moment at a specified location of a beam

L = input ('Please enter the span : ');


L1 = input('Please enter the first distance : ');
P = input ('Please enter the load intensity : ');
M_dist = input ('Please enter the distance of the moment point : ');

[RA,RB] = calrarb(P,L1,L); Function that return multiple values


Moment = calmoment(M_dist,RA,P,L1,L); Function that return single value
displaymoment(M_dist,Moment); Function without returning value
calrarb.m
function [RA RB] = calrarb(load,span1,span)
RA = load*(span1)/span;
RB = load-RA;
fprintf ('RA = %.2fKn and RB = %.2fKn\n',RA,RB) displaymoment.m
end function displaymoment(M_dist,Moment)
%This function is to display the value of moment at the specified length
fprintf('The moment at %.2fm is %.2fkN\n', M_dist, Moment)
calmoment.m
end M = calmoment(M_dist,RA,P,L1,L)
function
if (M_dist<L1)
M = RA*M_dist;
else
M = RA*M_dist-P*(M_dist-L1);
end
end
Output
>> Calculatemoment

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 : 3
RA = 5.00Kn and RB = 5.00Kn
The moment at 3.00m is 15.00Kn
Calculatemoment.m
function Moment = Calculatemoment(L,L1,P,M_dist)
%This function is to calculate the moment at a specified location of a beam

[RA,RB] = calrarb(P,L1,L); Function that return multiple values


Moment = calmoment(M_dist,RA,P,L1,L); Function that return single value
displaymoment(M_dist,Moment); Function without returning value
end
function [RA RB] = calrarb(load,span1,span)
RA = load*(span1)/span;
RB = load-RA;
fprintf ('RA = %.2fKn and RB = %.2fKn\n',RA,RB)
end
function M = calmoment(M_dist,RA,P,L1,L)
if (M_dist<L1)
M = RA*M_dist;
else
M = RA*M_dist-P*(M_dist-L1);
end
end
function displaymoment(M_dist,Moment)
%This function is to display the value of moment at the specified length
fprintf('The moment at %.2fm is %.2fkN\n', M_dist, Moment)
end
Output
>> Calculatemoment(10,5,10,3)

RA = 5.00Kn and RB = 5.00Kn


The moment at 3.00m is 15.00Kn

The function can be further utilised by


L = 10;
x = 0:L;
for i = 1:length(x)
Mx(i) = Calculatemoment(L,5,10,x(i))
end
plot(x,Mx)
5.2.2: Variable scope
• VARIABLE SCOPE refers to the extent of code in which a variable
can be referenced (accessed and modified).
• MATLAB stores variables in parts of memory called Workspace
• To check the existence of variable, use command whos

Base Workspace Function workspace

• is part of memory that is used • stores variables generated from


when commands are entered at function
the prompt or from scripts. • Variable in function workspace
• All variables can be cleared will be cleared once function
using command clear finished executing
• This workspace is kept separate
to protect the integrity of data
used by function.

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.

• The scope of local variables is limited to the function in which


they are defined. If the function contains nested functions, the
code in the nested functions can access all variables defined in
their "parent" function

• Local variables are not available at the command line or to any


other function. However, there are ways to share data between
functions or workspaces.
II. Global variable
• Global variables are variables that you can access from functions
or from the command line. They have their own workspace, which
is separate from the base and function workspaces.

• However, global variables carry notable risks.

 Any function can access and update a global variable.


Other functions that use the variable might return
unexpected results.

 If you unintentionally give a "new" global variable the


same name as an existing global variable, one function can
overwrite the values expected by another. This error is
difficult to diagnose.
Base Workspace
• When a script is executed from the MATLAB prompt in the command
window, the script uses the base workspace.
• Any variable created in the base workspace remain in the base workspace
after the script complete executed

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

P in function workspace (local variable) is


change to 50
User-Defined Functions (UDF)

PART 3 – NESTED FUNCTION


5.3 Nested Function
What Are Nested Functions?
A nested function is a function that is completely contained within a parent
function. Any function in a program file can include a nested function.

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

Create a program to calculate the centroid and moment inertia of a U


section
B2

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;

% calculate areas function calybar


a1=calarea(b1,h1); %this subfunction is to calculate Ybar
a2=calarea(b2,h2); ybar=(a1*y1-a2*y2)/(a1-a2);
% calc Y bar caltd(ybar)
end
[d1,d2,ybar] = caltransD(a1,y1,a2,y2);
function caltd(ybar)
%this subfunction is calculate transfer distance d1 and d2
i1=b1*h1^3/12; transd1 = y1-ybar;
i2=b2*h2^3/12; transd2 = y2-ybar;
ixx=(i1+a1*d1^2)- (i2+a2*d2^2); end
fprintf('Ybar is at %f and Ix is %.1f
mm^4\n',ybar,ixx) end

You might also like