You are on page 1of 11

Computer Programming

(CSC209)
Lecture (14)
User Define Functions in MATLAB

Dr.Anwar Hassan Ibrahim


Outline
1. User Defined functions
Definition and general expression
2. Application
Examples
Understanding Functions in MATLAB
A function is a group of statements that
together perform a task.
In MATLAB, functions are defined in
separate files.
Syntax of function
function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)
General expression
Function[output] = myfile(input)

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

You might also like