SlideShare a Scribd company logo
CSCI 101
Programmer-Defined Functions in
MATLAB
Outline
• Why programmer-defined functions?
• Simple Custom Functions
• Script vs Function
• Modular Programming
Why programmer-defined functions?
% Calculate x!/y!
fx=1;
for i=1:x
fx=fx*i;
end
fy=1;
for i=1:y
fy=fy*i;
end
Z=fx/fy;
disp(Z);
Using functions
% Calculate x!/y!
fx=fact(x);
fy=fact(y);
Z=fx/fy;
disp(Z);
• Less errors
• Better code organization
• More readable code
• Reuse of my functions
• Facilitate writing powerful/longer
programs
Functions Examples
MATLAB’s Built-in
Y=sqrt(x);
Y=round(x);
Y=pow(x,3);
Y=rem(x,2);
Programmer-defined
fx=fact(x);
rad= degree2rad(deg);
deg=rad2degree(rad);
d=dist(x1,y1,x2,y2);
Simple Custom Functions
Definition: fact calculates the factorial of a number
Input: a number (x)
Output: factorial of x (fx)
Function body:
function fx=fact(x)
% calculates the factorial of a number
fx=1;
for i=1:x
fx=fx*i;
end
end
fx=1;
for i=1:x
fx=fx*i;
end
Simple Custom Functions
• Functions are contained in M-files
• The function name and file name should match
– so the function fact should be in fact.m
• For help about the distance function use
>> help fact
• Now in matlab I can use it the same way as the built-in function
>> f=fact(5)
120
function fx = fact(x)
% fact calculates the factorial of x
fx=1;
for i=1:x
fx=fx*i;
end
end
See MATLAB 
Simple Custom Functions
function rad= degree2rad(deg)
%degree2rad converts the input degree into radians
rad=deg*pi/180;
end
function deg= rad2degree(rad)
%rad2degree converts the input radians into degrees
deg=rad*180/pi;
end
function dist = distance(x1, y1, x2, y2)
%distance calculates the distance between two points (x1,y1) and (x2, y2)
dist = sqrt((x2-x1)^2+(y2-y1)^2);
end
Programmer-Defined Functions in
MATLAB
(Part 2)
By
Elsayed Hemayed
Computer Engineering Dept
Faculty of Engineering
Cairo University, Giza, Egypt
Error Check Inputs
function x = correctInput(msg,low,high)
% correctInput prompt the user using msg for an input and
% error check to make sure it is >= low and <=high
x=input(msg);
while x<low || x> high
fprintf('Error! ');
x=input(msg);
end
end
>> x=correctInput('enter num:',0,10);
enter num:-5
Error! enter num:11
Error! enter num:4
>>
>> x
x =
4
correctInput.m
 Command Window
See MATLAB 
Custom Function with no return
function drawLine(n,ch)
% draw line of length n using the character ch.
for i=1 to n
fprintf(‘%s’,ch);
end
fprintf(‘n’);
>> drawLine (5,’*’);
*****
>> drawLine (10,’X’);
XXXXXXXXXX
>> drawLine(5,’-x-’);
-x--x--x--x--x-
drawLine.m
 Command Window
Custom Function with no input
function x=getPositiveNumber
% read positive number from the user
x=input(‘Enter positive number:’);
while x<0
fprintf('Error! ');
x=input(‘Enter positive number:’);
end
end
>> x=getPositiveNumber
Enter positive number:-3
Error! Enter positive number:-5
Error! Enter positive number:5
x =
5
 Command Window
getPositiveNumber.m
Custom Function with neither input
nor return
function drawFixedLine
% draw a line of fixed length 30 using the shape -x-.
for i=1:30
fprintf('-x-');
end
fprintf('n');
end
>> drawFixedLine
-x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x-
>> drawFixedLine
-x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x-
Command Window
drawFixedLine.m
Custom Function with more returns
function [large, small] = sort2(x,y)
%sort2 compares the two inputs and return them sorted, larger first.
if x>=y
large=x;
small=y;
else
large=y;
small=x;
end
end
>> [x,w]=sort2(5,10)
x =
10
w =
5
>> [x,w]=sort2(10,5)
x =
10
w =
5
sort2.m
Custom (User-Defined) Functions
function [out_arg1, out_arg2, …]
= fname(in_arg1, in_arg2, …)
• The word function is a keyword.
• [out_arg1, out_arg2, …] is the output
argument list
• fname is the name of the function
• (in_arg1, in_arg2, …) is the input argument
list
– in_arg1, in_arg2, etc. are called “dummy arguments”
because they are filled will values when the function is
called
Programmer-Defined Functions in
MATLAB
(Part 3)
By
Elsayed Hemayed
Computer Engineering Dept
Faculty of Engineering
Cairo University, Giza, Egypt
Local Workspace
Script
w=input(‘enter a number:’);
y=fact(w);
disp(y);
Function
function fx = fact(x)
%fact calculates the factorial of x
fx=1;
for i=1:x
fx=fx*i;
end
end
Command Window Workspace
contains w and y.
So fx, x, and i are not known here
Function fact Workspace contains fx, x, and i
When a function reaches the end of execution (and returns the output argument), the
function space— local space—is deleted.
Script Vs. Function
Script
• A script is executed line-
byline just as if you are
typing it into the Command
Window
• The value of a variable in a
script is stored in the
Command Window
Workspace
Function
• A function has its own
private (local) function
workspace that does not
interact with the workspace
of other functions or the
Command Window
workspace
• Variables are not shared
between workspaces even if
they have the same name
Modular Programming
Write program that takes the student grade (out of 100) in Math,
Science, and English and prints ‘Excellent’ if greater than or equal 90%,
‘Very Good’ if greater than or equal 80% and smaller than 90%, ‘Good’
if greater than or equal 70 and smaller than 80%, ‘Fair’ if greater than
or equal 60% and smaller than 70%,’Fail’ if lower than 60%.
Sample Input/Output:
Enter Math grade from 0 to 100:94
Enter Science grade from 0 to 100:87
Enter English grade from 0 to 100:77
You got Excellent in Math
You got Very Good in Science
You got Good in English
Modular Programming
Write program that takes the student grade (out of 100) in Math, Science, and English
m=correctInput('Enter math grade from 0 to 100:',0,100);
s=correctInput('Enter science grade from 0 to 100:',0,100);
e=correctInput('Enter english grade from 0 to 100:',0,10);
and prints ‘Excellent’ if greater than or equal 90%, ‘Very Good’ if greater than or equal
80% and smaller than 90%, ‘Good’ if greater than or equal 70 and smaller than 80%,
‘Fair’ if greater than or equal 60% and smaller than 70%,’Fail’ if lower than 60%.
mr=grade2rank(m); % A function to convert grade numeric to alphanumeric
sr=grade2rank(s);
er=grade2rank(e);
fprintf('You got %s in mathn',mr);
fprintf('You got %s in sciencen',sr);
fprintf('You got %s in englishn',er);
Use Functions for Clean and Organized
Code (Modular Programs)
m=correctInput('Enter math grade from 0 to 100:',0,100);
s=correctInput('Enter science grade from 0 to 100:',0,100);
e=correctInput('Enter english grade from 0 to 100:',0,100);
mr=grade2rank(m);
sr=grade2rank(s);
er=grade2rank(e);
fprintf('You got %s in mathn',mr);
fprintf('You got %s in sciencen',sr);
fprintf('You got %s in englishn',er);
Main
program
correctInput grade2rank
fn3
Function: grade2rank
function r=grade2rank(x)
% calculate the corresponding rank of the grade x
if x>=90
r='Ecellent';
elseif x>=80
r='Very Good';
elseif x>=70
r='Good';
elseif x>=60
r='Fair';
else
r='Fail';
end
end
See MATLAB 

More Related Content

PDF
Chapter 4 : Balagurusamy Programming ANSI in C
PDF
Chapter 5 exercises Balagurusamy Programming ANSI in c
TXT
rtrtrNew text document
RTF
PDF
Chapter 3 : Balagurusamy Programming ANSI in C
DOCX
Core programming in c
PPT
Loop Statements [5] M
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 5 exercises Balagurusamy Programming ANSI in c
rtrtrNew text document
Chapter 3 : Balagurusamy Programming ANSI in C
Core programming in c
Loop Statements [5] M

What's hot (19)

PDF
Chapter 6 Balagurusamy Programming ANSI in c
DOCX
Cs291 assignment solution
DOC
Slide07 repetitions
PDF
Chapter 2 : Balagurusamy_ Programming ANsI in C
PPTX
C programming codes for the class assignment
DOCX
C Programming
PPTX
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
PDF
CP Handout#7
DOCX
Write a program to check a given number is prime or not
PPT
Flow Chart & Input Output Statement [3] M
PPTX
FLOW OF CONTROL-NESTED IFS IN PYTHON
PPTX
Input Output Management In C Programming
PDF
C Programming Example
PPTX
C Programming Example
PDF
88 c-programs
DOCX
C programming Lab 2
DOCX
Programming fundamentals
PPT
Mesics lecture 5 input – output in ‘c’
DOCX
programs of c www.eakanchha.com
Chapter 6 Balagurusamy Programming ANSI in c
Cs291 assignment solution
Slide07 repetitions
Chapter 2 : Balagurusamy_ Programming ANsI in C
C programming codes for the class assignment
C Programming
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
CP Handout#7
Write a program to check a given number is prime or not
Flow Chart & Input Output Statement [3] M
FLOW OF CONTROL-NESTED IFS IN PYTHON
Input Output Management In C Programming
C Programming Example
C Programming Example
88 c-programs
C programming Lab 2
Programming fundamentals
Mesics lecture 5 input – output in ‘c’
programs of c www.eakanchha.com
Ad

Similar to Csci101 lect08a matlab_programs (20)

PPTX
Csci101 lect08b matlab_programs
PPTX
introduction to c programming and C History.pptx
PPTX
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
PPTX
Csci101 lect02 selection_andlooping
DOC
Programming egs
PDF
Numerical analysis
PPTX
Introduction to Basic C programming 02
PPTX
Python 04-ifelse-return-input-strings.pptx
PDF
Programming Fundamentals Decisions
PDF
C programs
PPTX
C language operator
PDF
C Language Lecture 17
PDF
LET US C (5th EDITION) CHAPTER 2 ANSWERS
PPTX
Operators1.pptx
DOC
C important questions
PPTX
Operators inc c language
PPTX
Operators and expressions in c language
PDF
C Language Lecture 3
DOCX
Practical write a c program to reverse a given number
Csci101 lect08b matlab_programs
introduction to c programming and C History.pptx
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Csci101 lect02 selection_andlooping
Programming egs
Numerical analysis
Introduction to Basic C programming 02
Python 04-ifelse-return-input-strings.pptx
Programming Fundamentals Decisions
C programs
C language operator
C Language Lecture 17
LET US C (5th EDITION) CHAPTER 2 ANSWERS
Operators1.pptx
C important questions
Operators inc c language
Operators and expressions in c language
C Language Lecture 3
Practical write a c program to reverse a given number
Ad

More from Elsayed Hemayed (20)

PPTX
14 cie552 camera_calibration
PPTX
12 cie552 object_recognition
PPTX
11 cie552 image_featuresii_sift
PPTX
10 cie552 image_featuresii_corner
PPTX
09 cie552 image_featuresi
PPTX
08 cie552 image_segmentation
PPTX
07 cie552 image_mosaicing
PPTX
06 cie552 image_manipulation
PPTX
05 cie552 image_enhancement
PPTX
04 cie552 image_filtering_frequency
PPTX
03 cie552 image_filtering_spatial
PPTX
02 cie552 image_andcamera
PPTX
01 cie552 introduction
PPTX
Csci101 lect04 advanced_selection
PPTX
Csci101 lect10 algorithms_iii
PPTX
Csci101 lect09 vectorized_code
PPTX
Csci101 lect07 algorithms_ii
PPTX
Csci101 lect06 advanced_looping
PPTX
Csci101 lect05 formatted_output
PPTX
Csci101 lect03 algorithms_i
14 cie552 camera_calibration
12 cie552 object_recognition
11 cie552 image_featuresii_sift
10 cie552 image_featuresii_corner
09 cie552 image_featuresi
08 cie552 image_segmentation
07 cie552 image_mosaicing
06 cie552 image_manipulation
05 cie552 image_enhancement
04 cie552 image_filtering_frequency
03 cie552 image_filtering_spatial
02 cie552 image_andcamera
01 cie552 introduction
Csci101 lect04 advanced_selection
Csci101 lect10 algorithms_iii
Csci101 lect09 vectorized_code
Csci101 lect07 algorithms_ii
Csci101 lect06 advanced_looping
Csci101 lect05 formatted_output
Csci101 lect03 algorithms_i

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
01-Introduction-to-Information-Management.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
GDM (1) (1).pptx small presentation for students
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Complications of Minimal Access Surgery at WLH
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Microbial diseases, their pathogenesis and prophylaxis
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
01-Introduction-to-Information-Management.pdf
TR - Agricultural Crops Production NC III.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Institutional Correction lecture only . . .
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
GDM (1) (1).pptx small presentation for students
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Structure & Organelles in detailed.
O5-L3 Freight Transport Ops (International) V1.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
102 student loan defaulters named and shamed – Is someone you know on the list?
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Complications of Minimal Access Surgery at WLH

Csci101 lect08a matlab_programs

  • 2. Outline • Why programmer-defined functions? • Simple Custom Functions • Script vs Function • Modular Programming
  • 3. Why programmer-defined functions? % Calculate x!/y! fx=1; for i=1:x fx=fx*i; end fy=1; for i=1:y fy=fy*i; end Z=fx/fy; disp(Z); Using functions % Calculate x!/y! fx=fact(x); fy=fact(y); Z=fx/fy; disp(Z); • Less errors • Better code organization • More readable code • Reuse of my functions • Facilitate writing powerful/longer programs
  • 5. Simple Custom Functions Definition: fact calculates the factorial of a number Input: a number (x) Output: factorial of x (fx) Function body: function fx=fact(x) % calculates the factorial of a number fx=1; for i=1:x fx=fx*i; end end fx=1; for i=1:x fx=fx*i; end
  • 6. Simple Custom Functions • Functions are contained in M-files • The function name and file name should match – so the function fact should be in fact.m • For help about the distance function use >> help fact • Now in matlab I can use it the same way as the built-in function >> f=fact(5) 120 function fx = fact(x) % fact calculates the factorial of x fx=1; for i=1:x fx=fx*i; end end See MATLAB 
  • 7. Simple Custom Functions function rad= degree2rad(deg) %degree2rad converts the input degree into radians rad=deg*pi/180; end function deg= rad2degree(rad) %rad2degree converts the input radians into degrees deg=rad*180/pi; end function dist = distance(x1, y1, x2, y2) %distance calculates the distance between two points (x1,y1) and (x2, y2) dist = sqrt((x2-x1)^2+(y2-y1)^2); end
  • 8. Programmer-Defined Functions in MATLAB (Part 2) By Elsayed Hemayed Computer Engineering Dept Faculty of Engineering Cairo University, Giza, Egypt
  • 9. Error Check Inputs function x = correctInput(msg,low,high) % correctInput prompt the user using msg for an input and % error check to make sure it is >= low and <=high x=input(msg); while x<low || x> high fprintf('Error! '); x=input(msg); end end >> x=correctInput('enter num:',0,10); enter num:-5 Error! enter num:11 Error! enter num:4 >> >> x x = 4 correctInput.m  Command Window See MATLAB 
  • 10. Custom Function with no return function drawLine(n,ch) % draw line of length n using the character ch. for i=1 to n fprintf(‘%s’,ch); end fprintf(‘n’); >> drawLine (5,’*’); ***** >> drawLine (10,’X’); XXXXXXXXXX >> drawLine(5,’-x-’); -x--x--x--x--x- drawLine.m  Command Window
  • 11. Custom Function with no input function x=getPositiveNumber % read positive number from the user x=input(‘Enter positive number:’); while x<0 fprintf('Error! '); x=input(‘Enter positive number:’); end end >> x=getPositiveNumber Enter positive number:-3 Error! Enter positive number:-5 Error! Enter positive number:5 x = 5  Command Window getPositiveNumber.m
  • 12. Custom Function with neither input nor return function drawFixedLine % draw a line of fixed length 30 using the shape -x-. for i=1:30 fprintf('-x-'); end fprintf('n'); end >> drawFixedLine -x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x- >> drawFixedLine -x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x--x- Command Window drawFixedLine.m
  • 13. Custom Function with more returns function [large, small] = sort2(x,y) %sort2 compares the two inputs and return them sorted, larger first. if x>=y large=x; small=y; else large=y; small=x; end end >> [x,w]=sort2(5,10) x = 10 w = 5 >> [x,w]=sort2(10,5) x = 10 w = 5 sort2.m
  • 14. Custom (User-Defined) Functions function [out_arg1, out_arg2, …] = fname(in_arg1, in_arg2, …) • The word function is a keyword. • [out_arg1, out_arg2, …] is the output argument list • fname is the name of the function • (in_arg1, in_arg2, …) is the input argument list – in_arg1, in_arg2, etc. are called “dummy arguments” because they are filled will values when the function is called
  • 15. Programmer-Defined Functions in MATLAB (Part 3) By Elsayed Hemayed Computer Engineering Dept Faculty of Engineering Cairo University, Giza, Egypt
  • 16. Local Workspace Script w=input(‘enter a number:’); y=fact(w); disp(y); Function function fx = fact(x) %fact calculates the factorial of x fx=1; for i=1:x fx=fx*i; end end Command Window Workspace contains w and y. So fx, x, and i are not known here Function fact Workspace contains fx, x, and i When a function reaches the end of execution (and returns the output argument), the function space— local space—is deleted.
  • 17. Script Vs. Function Script • A script is executed line- byline just as if you are typing it into the Command Window • The value of a variable in a script is stored in the Command Window Workspace Function • A function has its own private (local) function workspace that does not interact with the workspace of other functions or the Command Window workspace • Variables are not shared between workspaces even if they have the same name
  • 18. Modular Programming Write program that takes the student grade (out of 100) in Math, Science, and English and prints ‘Excellent’ if greater than or equal 90%, ‘Very Good’ if greater than or equal 80% and smaller than 90%, ‘Good’ if greater than or equal 70 and smaller than 80%, ‘Fair’ if greater than or equal 60% and smaller than 70%,’Fail’ if lower than 60%. Sample Input/Output: Enter Math grade from 0 to 100:94 Enter Science grade from 0 to 100:87 Enter English grade from 0 to 100:77 You got Excellent in Math You got Very Good in Science You got Good in English
  • 19. Modular Programming Write program that takes the student grade (out of 100) in Math, Science, and English m=correctInput('Enter math grade from 0 to 100:',0,100); s=correctInput('Enter science grade from 0 to 100:',0,100); e=correctInput('Enter english grade from 0 to 100:',0,10); and prints ‘Excellent’ if greater than or equal 90%, ‘Very Good’ if greater than or equal 80% and smaller than 90%, ‘Good’ if greater than or equal 70 and smaller than 80%, ‘Fair’ if greater than or equal 60% and smaller than 70%,’Fail’ if lower than 60%. mr=grade2rank(m); % A function to convert grade numeric to alphanumeric sr=grade2rank(s); er=grade2rank(e); fprintf('You got %s in mathn',mr); fprintf('You got %s in sciencen',sr); fprintf('You got %s in englishn',er);
  • 20. Use Functions for Clean and Organized Code (Modular Programs) m=correctInput('Enter math grade from 0 to 100:',0,100); s=correctInput('Enter science grade from 0 to 100:',0,100); e=correctInput('Enter english grade from 0 to 100:',0,100); mr=grade2rank(m); sr=grade2rank(s); er=grade2rank(e); fprintf('You got %s in mathn',mr); fprintf('You got %s in sciencen',sr); fprintf('You got %s in englishn',er); Main program correctInput grade2rank fn3
  • 21. Function: grade2rank function r=grade2rank(x) % calculate the corresponding rank of the grade x if x>=90 r='Ecellent'; elseif x>=80 r='Very Good'; elseif x>=70 r='Good'; elseif x>=60 r='Fair'; else r='Fail'; end end See MATLAB 