SlideShare a Scribd company logo
1 of 21
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

What's hot

Chapter 6 Balagurusamy Programming ANSI in c
Chapter 6  Balagurusamy Programming ANSI  in cChapter 6  Balagurusamy Programming ANSI  in c
Chapter 6 Balagurusamy Programming ANSI in cBUBT
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solutionKuntal Bhowmick
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitionsaltwirqi
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in CBUBT
 
C programming codes for the class assignment
C programming codes for the class assignmentC programming codes for the class assignment
C programming codes for the class assignmentZenith SVG
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]vikram mahendra
 
Write a program to check a given number is prime or not
Write a program to check a given number is prime or notWrite a program to check a given number is prime or not
Write a program to check a given number is prime or notaluavi
 
Flow Chart & Input Output Statement [3] M
Flow Chart & Input Output Statement [3] MFlow Chart & Input Output Statement [3] M
Flow Chart & Input Output Statement [3] Mecko_disasterz
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONvikram mahendra
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C ProgrammingKamal Acharya
 
C programming Lab 2
C programming Lab 2C programming Lab 2
C programming Lab 2Zaibi Gondal
 
Programming fundamentals
Programming fundamentalsProgramming fundamentals
Programming fundamentalsZaibi Gondal
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’eShikshak
 
programs of c www.eakanchha.com
 programs of c www.eakanchha.com programs of c www.eakanchha.com
programs of c www.eakanchha.comAkanchha Agrawal
 

What's hot (20)

Loop Statements [5] M
Loop Statements [5] MLoop Statements [5] M
Loop Statements [5] M
 
Chapter 6 Balagurusamy Programming ANSI in c
Chapter 6  Balagurusamy Programming ANSI  in cChapter 6  Balagurusamy Programming ANSI  in c
Chapter 6 Balagurusamy Programming ANSI in c
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in C
 
C programming codes for the class assignment
C programming codes for the class assignmentC programming codes for the class assignment
C programming codes for the class assignment
 
C Programming
C ProgrammingC Programming
C Programming
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
 
CP Handout#7
CP Handout#7CP Handout#7
CP Handout#7
 
Write a program to check a given number is prime or not
Write a program to check a given number is prime or notWrite a program to check a given number is prime or not
Write a program to check a given number is prime or not
 
Flow Chart & Input Output Statement [3] M
Flow Chart & Input Output Statement [3] MFlow Chart & Input Output Statement [3] M
Flow Chart & Input Output Statement [3] M
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHON
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
C Programming Example
C Programming ExampleC Programming Example
C Programming Example
 
C Programming Example
C Programming Example C Programming Example
C Programming Example
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
C programming Lab 2
C programming Lab 2C programming Lab 2
C programming Lab 2
 
Programming fundamentals
Programming fundamentalsProgramming fundamentals
Programming fundamentals
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 
programs of c www.eakanchha.com
 programs of c www.eakanchha.com programs of c www.eakanchha.com
programs of c www.eakanchha.com
 

Similar to Csci101 lect08a matlab_programs

Csci101 lect08b matlab_programs
Csci101 lect08b matlab_programsCsci101 lect08b matlab_programs
Csci101 lect08b matlab_programsElsayed Hemayed
 
introduction to c programming and C History.pptx
introduction to c programming and C History.pptxintroduction to c programming and C History.pptx
introduction to c programming and C History.pptxManojKhadilkar1
 
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTESUnit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTESLeahRachael
 
Csci101 lect02 selection_andlooping
Csci101 lect02 selection_andloopingCsci101 lect02 selection_andlooping
Csci101 lect02 selection_andloopingElsayed Hemayed
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysisVishal Singh
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02Wingston
 
Python 04-ifelse-return-input-strings.pptx
Python 04-ifelse-return-input-strings.pptxPython 04-ifelse-return-input-strings.pptx
Python 04-ifelse-return-input-strings.pptxTseChris
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions imtiazalijoono
 
C language operator
C language operatorC language operator
C language operatorcprogram
 
LET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERSLET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERSKavyaSharma65
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
Operators inc c language
Operators inc c languageOperators inc c language
Operators inc c languageTanmay Modi
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given numberMainak Sasmal
 

Similar to Csci101 lect08a matlab_programs (20)

Csci101 lect08b matlab_programs
Csci101 lect08b matlab_programsCsci101 lect08b matlab_programs
Csci101 lect08b matlab_programs
 
introduction to c programming and C History.pptx
introduction to c programming and C History.pptxintroduction to c programming and C History.pptx
introduction to c programming and C History.pptx
 
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTESUnit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
 
Csci101 lect02 selection_andlooping
Csci101 lect02 selection_andloopingCsci101 lect02 selection_andlooping
Csci101 lect02 selection_andlooping
 
Programming egs
Programming egs Programming egs
Programming egs
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Python 04-ifelse-return-input-strings.pptx
Python 04-ifelse-return-input-strings.pptxPython 04-ifelse-return-input-strings.pptx
Python 04-ifelse-return-input-strings.pptx
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
C programs
C programsC programs
C programs
 
C language operator
C language operatorC language operator
C language operator
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
LET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERSLET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERS
 
C
CC
C
 
Operators1.pptx
Operators1.pptxOperators1.pptx
Operators1.pptx
 
C important questions
C important questionsC important questions
C important questions
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Operators inc c language
Operators inc c languageOperators inc c language
Operators inc c language
 
C Language Lecture 3
C Language Lecture  3C Language Lecture  3
C Language Lecture 3
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 

More from Elsayed Hemayed

14 cie552 camera_calibration
14 cie552 camera_calibration14 cie552 camera_calibration
14 cie552 camera_calibrationElsayed Hemayed
 
12 cie552 object_recognition
12 cie552 object_recognition12 cie552 object_recognition
12 cie552 object_recognitionElsayed Hemayed
 
11 cie552 image_featuresii_sift
11 cie552 image_featuresii_sift11 cie552 image_featuresii_sift
11 cie552 image_featuresii_siftElsayed Hemayed
 
10 cie552 image_featuresii_corner
10 cie552 image_featuresii_corner10 cie552 image_featuresii_corner
10 cie552 image_featuresii_cornerElsayed Hemayed
 
09 cie552 image_featuresi
09 cie552 image_featuresi09 cie552 image_featuresi
09 cie552 image_featuresiElsayed Hemayed
 
08 cie552 image_segmentation
08 cie552 image_segmentation08 cie552 image_segmentation
08 cie552 image_segmentationElsayed Hemayed
 
07 cie552 image_mosaicing
07 cie552 image_mosaicing07 cie552 image_mosaicing
07 cie552 image_mosaicingElsayed Hemayed
 
06 cie552 image_manipulation
06 cie552 image_manipulation06 cie552 image_manipulation
06 cie552 image_manipulationElsayed Hemayed
 
05 cie552 image_enhancement
05 cie552 image_enhancement05 cie552 image_enhancement
05 cie552 image_enhancementElsayed Hemayed
 
04 cie552 image_filtering_frequency
04 cie552 image_filtering_frequency04 cie552 image_filtering_frequency
04 cie552 image_filtering_frequencyElsayed Hemayed
 
03 cie552 image_filtering_spatial
03 cie552 image_filtering_spatial03 cie552 image_filtering_spatial
03 cie552 image_filtering_spatialElsayed Hemayed
 
02 cie552 image_andcamera
02 cie552 image_andcamera02 cie552 image_andcamera
02 cie552 image_andcameraElsayed Hemayed
 
Csci101 lect04 advanced_selection
Csci101 lect04 advanced_selectionCsci101 lect04 advanced_selection
Csci101 lect04 advanced_selectionElsayed Hemayed
 
Csci101 lect10 algorithms_iii
Csci101 lect10 algorithms_iiiCsci101 lect10 algorithms_iii
Csci101 lect10 algorithms_iiiElsayed Hemayed
 
Csci101 lect09 vectorized_code
Csci101 lect09 vectorized_codeCsci101 lect09 vectorized_code
Csci101 lect09 vectorized_codeElsayed Hemayed
 
Csci101 lect07 algorithms_ii
Csci101 lect07 algorithms_iiCsci101 lect07 algorithms_ii
Csci101 lect07 algorithms_iiElsayed Hemayed
 
Csci101 lect06 advanced_looping
Csci101 lect06 advanced_loopingCsci101 lect06 advanced_looping
Csci101 lect06 advanced_loopingElsayed Hemayed
 
Csci101 lect05 formatted_output
Csci101 lect05 formatted_outputCsci101 lect05 formatted_output
Csci101 lect05 formatted_outputElsayed Hemayed
 
Csci101 lect03 algorithms_i
Csci101 lect03 algorithms_iCsci101 lect03 algorithms_i
Csci101 lect03 algorithms_iElsayed Hemayed
 

More from Elsayed Hemayed (20)

14 cie552 camera_calibration
14 cie552 camera_calibration14 cie552 camera_calibration
14 cie552 camera_calibration
 
12 cie552 object_recognition
12 cie552 object_recognition12 cie552 object_recognition
12 cie552 object_recognition
 
11 cie552 image_featuresii_sift
11 cie552 image_featuresii_sift11 cie552 image_featuresii_sift
11 cie552 image_featuresii_sift
 
10 cie552 image_featuresii_corner
10 cie552 image_featuresii_corner10 cie552 image_featuresii_corner
10 cie552 image_featuresii_corner
 
09 cie552 image_featuresi
09 cie552 image_featuresi09 cie552 image_featuresi
09 cie552 image_featuresi
 
08 cie552 image_segmentation
08 cie552 image_segmentation08 cie552 image_segmentation
08 cie552 image_segmentation
 
07 cie552 image_mosaicing
07 cie552 image_mosaicing07 cie552 image_mosaicing
07 cie552 image_mosaicing
 
06 cie552 image_manipulation
06 cie552 image_manipulation06 cie552 image_manipulation
06 cie552 image_manipulation
 
05 cie552 image_enhancement
05 cie552 image_enhancement05 cie552 image_enhancement
05 cie552 image_enhancement
 
04 cie552 image_filtering_frequency
04 cie552 image_filtering_frequency04 cie552 image_filtering_frequency
04 cie552 image_filtering_frequency
 
03 cie552 image_filtering_spatial
03 cie552 image_filtering_spatial03 cie552 image_filtering_spatial
03 cie552 image_filtering_spatial
 
02 cie552 image_andcamera
02 cie552 image_andcamera02 cie552 image_andcamera
02 cie552 image_andcamera
 
01 cie552 introduction
01 cie552 introduction01 cie552 introduction
01 cie552 introduction
 
Csci101 lect04 advanced_selection
Csci101 lect04 advanced_selectionCsci101 lect04 advanced_selection
Csci101 lect04 advanced_selection
 
Csci101 lect10 algorithms_iii
Csci101 lect10 algorithms_iiiCsci101 lect10 algorithms_iii
Csci101 lect10 algorithms_iii
 
Csci101 lect09 vectorized_code
Csci101 lect09 vectorized_codeCsci101 lect09 vectorized_code
Csci101 lect09 vectorized_code
 
Csci101 lect07 algorithms_ii
Csci101 lect07 algorithms_iiCsci101 lect07 algorithms_ii
Csci101 lect07 algorithms_ii
 
Csci101 lect06 advanced_looping
Csci101 lect06 advanced_loopingCsci101 lect06 advanced_looping
Csci101 lect06 advanced_looping
 
Csci101 lect05 formatted_output
Csci101 lect05 formatted_outputCsci101 lect05 formatted_output
Csci101 lect05 formatted_output
 
Csci101 lect03 algorithms_i
Csci101 lect03 algorithms_iCsci101 lect03 algorithms_i
Csci101 lect03 algorithms_i
 

Recently uploaded

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Recently uploaded (20)

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

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