Professional Documents
Culture Documents
(CSC209)
Lecture (14)
User Define Functions in MATLAB
Commands
End
Example of Function File
function[A]= sum_x(c,d,e,f)
A=c+d+e+f
end
>> A=sum_x(1,2,3,4)
A=
10
Example (2)
Write a user define function to define the area of circle
Solution
function[A] = Area_c(r)
A=pi*r^2
end
>> Area_c(2)
A=
12.5664
5
Example (3)
Use MatLab User defined function to find Cylinder
volume (V) and surface area (A) for the figure
bellow. Assume radius of 5 m and height of 13 m.
Consider
Solution
function[V,A] = A_V_cylinder(r,h)
V=pi*r^2*h;
A=2*pi*r*(r+h);
end
6
Example (4)
Write a MATLAB code user defined function for
Pythagoras theorem to define hypotenuse
Solution
function[C] = hypotheo(a,b)
C=sqrt(a^2+b^2);
end
7
Example (5)
Write a MATLAB code through user defined
function to find the roots of quadratic equation
Solution
function[x1,x2] = quad_cal(a,b,c)
x1=(-b+sqrt(b^2-4*a*c))/(2*a);
x2=(-b-sqrt(b^2-4*a*c))/(2*a);
end
8
MATLAB script to Call functions
Calling functions using user define values
% Functions input
a =input('Enter a :');
b =input('Enter b :');
r =input('Enter r :');
h =input('Enter h :');
% functions output
C = hypotheo(a,b)
[V,A]= A_V_cylinder(r,h)
9
Tutorial
10
END
11