SlideShare a Scribd company logo
8
Most read
9
Most read
13
Most read
SESSION-7-8
User Defined Functions
in MATLAB
By: Prof. Ganesh Ingle
Course Main Topic/Chapters
Introduction User Defined Functions in MATLAB
Categories of Functions
Summary
User Defined Functions in MATLAB
Function: A function is a block of code that performs a specific task.
MATLAB allows you to define functions according to your need. These
functions are known as user-defined functions.
Advantages :
1. The subprogram are easier to write, understand and debug.
2. A function can call itself again. It is called a recursive function.
Many calculations can be done easily by using recursive functions
such as calculation of factorial of a number, etc.
3. Reduction in size of program due to program code of a function can
be used again and again, by calling it.
4. The complexity of the entire program can be divided into simple
subtask and then function subprograms can be written for each
subtask.
5. A library of a function can be designed and tested for use of every
programmer.
6. Code reusability
User Defined Functions in MATLAB
Function: A function is a group of statements that together perform a task.
In MATLAB, functions are defined in separate files. The name of the file
and of the function should be the same.
Functions operate on variables within their own workspace, which is also
called the local workspace, separate from the workspace you access at the
MATLAB command prompt which is called the base workspace.
Functions can accept more than one input arguments and may return more
than one output arguments.
Syntax of a function statement is −
function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)
Types of Functions
Functions
Predefined
Functions
Library Functions
Declared in header file
Body in .dll files
User Defined
Functions
Anonymous
Functions
Primary and
Sub-Functions
Nested
Functions
Recursive
Functions
Private
Functions
Types of Arguments
Basically, there are two types of arguments:
1.Actual arguments:
The variables declared in the function prototype or definition are known as
Formal arguments
2.Formal arguments :
The variable that are passed to the called function from the main function are
known as Actual arguments.
3.Local Variable
A local variable is a type of variable declared within programming block or
subroutines. It can only be used only inside that subroutine or code block in
which they were declared. The local variable exists until the block of the
function is in under execution. After that, it will be destroyed automatically.
4.Global variables:
Global variables are defined outside of a subroutine or function. The global
variable will hold its value throughout the lifetime of a program. They can be
accessed within any function defined for the program.
Types of Arguments
Basically, there are two types of arguments:
1.Actual arguments:
The variables declared in the function prototype or definition are known as
Formal arguments
2.Formal arguments :
The variable that are passed to the called function from the main function are
known as Actual arguments.
3.Local Variable
A local variable is a type of variable declared within programming block or
subroutines. It can only be used only inside that subroutine or code block in
which they were declared. The local variable exists until the block of the
function is in under execution. After that, it will be destroyed automatically.
4.Global variables:
Global variables are defined outside of a subroutine or function. The global
variable will hold its value throughout the lifetime of a program. They can be
accessed within any function defined for the program.
Global Variables
Global variables can be shared by more than one function. For this, you need to declare
the variable as global in all the functions.I f you want to access that variable from the
base workspace, then declare the variable at the command line.
The global declaration must occur before the variable is actually used in a function. It is a
good practice to use capital letters for the names of global variables to distinguish them
from other variables.
Example
Let us create a function file named average.m and type the following code in it
−
function avg = average(nums)
global TOTAL
avg = sum(nums)/TOTAL;
end
Create a script file and type the following code in it −
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
When you run the file, it will display the following result −
av = 35.500
Example
Example
The following function named mymax should be written in a file named mymax.m.
It takes five numbers as argument and returns the maximum of the numbers.
function max = mymax(n1, n2, n3, n4, n5)
%This function calculates the maximum of the five numbers given as input
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end
You can call the function as −
mymax(34, 78, 89, 23, 11)
Anonymous Functions
An anonymous function is like an inline function in traditional programming
languages, defined within a single MATLAB statement. It consists of a single MATLAB
expression and any number of input and output arguments. You can define an
anonymous function right at the MATLAB command line or within a function or
script. This way you can create simple functions without having to create a file for
them.
The syntax for creating an anonymous function from an expression is
f = @(arglist)expression
Example
In this example, we will write an anonymous function named power, which will take
two numbers as input and return first number raised to the power of the second
number.
Create a script file and type the following code in it −
power = @(x, n) x.^n;
result1 = power(7, 3)
result2 = power(49, 0.5)
result3 = power(10, -10)
result4 = power (4.5, 1.5)
When you run the file, it
displays −
result1 = 343
result2 = 7
result3 = 1.0000e-10
result4 = 9.5459
Primary and Sub-Functions
Any function other than an anonymous function must be defined within a file. Each
function file contains a required primary function that appears first and any
number of optional sub-functions that comes after the primary function and used
by it. Primary functions can be called from outside of the file that defines them,
either from command line or from other functions, but sub-functions cannot be
called from command line or other functions, outside the function file.
Sub-functions are visible only to the primary function and other sub-functions
within the function file that defines them.
Example
Let us write a function named quadratic that would calculate the roots of a
quadratic equation. The function would take three inputs, the quadratic co-
efficient, the linear co-efficient and the constant term. It would return the
roots.The function file quadratic.m will contain the primary function quadratic and
the sub-function disc, which calculates the discriminant.
Primary and Sub-Functions
Create a function file quadratic.m and type the following code in it −
function [x1,x2] = quadratic(a,b,c)
%this function returns the roots of
% a quadratic equation.
% It takes 3 input arguments
% which are the co-efficients of x2, x and the
%constant term
% It returns the roots
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic
function dis = disc(a,b,c)
%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function
You can call the above function from
command prompt as −
quadratic(2,4,-4)
MATLAB will execute the above
statement and return the following
result −
ans = 0.7321
Nested Functions
You can define functions within the body of another function. These are called
nested functions. A nested function contains any or all of the components of any
other function.
Nested functions are defined within the scope of another function and they share
access to the containing function's workspace.
A nested function follows the following syntax −
function x = A(p1, p2)
...
B(p2)
function y = B(p3)
...
end
...
end
Nested Functions
Example
Let us rewrite the function quadratic, from previous example, however, this time
the disc function will be a nested function.
Create a function file quadratic2.m and type the following code in it −
function [x1,x2] = quadratic2(a,b,c)
function disc % nested function
d = sqrt(b^2 - 4*a*c);
end % end of function disc
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of function quadratic2
You can call the above function from
command prompt as −
quadratic2(2,4,-4)
MATLAB will execute the above
statement and return the following
result −
ans = 0.73205
Private Functions
A private function is a primary function that is visible only to a limited group of
other functions. If you do not want to expose the implementation of a
function(s), you can create them as private functions.
Private functions reside in subfolders with the special name private.
They are visible only to functions in the parent folder.
Example
Let us rewrite the quadratic function. This time, however, the disc function
calculating the discriminant, will be a private function.
Create a subfolder named private in working directory. Store the following
function file disc.m in it −
function dis = disc(a,b,c)
%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function
Private Functions
Create a function quadratic3.m in your working directory and type the following
code in it −
function [x1,x2] = quadratic3(a,b,c)
%this function returns the roots of
% a quadratic equation.
% It takes 3 input arguments
% which are the co-efficient of x2, x and the constant term
% It returns the roots
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic3
You can call the above function from
command prompt as −
quadratic3(2,4,-4)
MATLAB will execute the above
statement and return the following
result −
ans = 0.73205
THANK YOU
Image Source
searchenterpriseai.techtarget.com
Wikipedia
https://www.w3resource.com/

More Related Content

PPT
Matlab Basic Tutorial
PPTX
MATLAB - Arrays and Matrices
PDF
MATLAB INTRODUCTION
PDF
Matlab Tutorial for Beginners - I
PPTX
An Introduction to MATLAB for beginners
PPT
Introduction to matlab
PPTX
Presentation on application of numerical method in our life
PPTX
Matlab ppt
Matlab Basic Tutorial
MATLAB - Arrays and Matrices
MATLAB INTRODUCTION
Matlab Tutorial for Beginners - I
An Introduction to MATLAB for beginners
Introduction to matlab
Presentation on application of numerical method in our life
Matlab ppt

What's hot (20)

PDF
Matlab-free course by Mohd Esa
PDF
Numerical Computing
PPSX
Matlab basic and image
PPT
Signal & systems
PPTX
Principle and working of a semiconductor laser
PPTX
Matlab ppt
PDF
Simulation of Wireless Communication Systems
PPTX
Introduction to matlab lecture 1 of 4
PPTX
Ic voltage regulators
PPT
Lecture 1 introduction to communication systems
PPT
Introduction to matlab
PPT
Matlab Tutorial.ppt
PPTX
Inroduction to HFSS
PPTX
Probability Density Function (PDF)
PPTX
Matching techniques
PDF
Amplitude Modulation using Multipliers and Envelope Detector
PDF
Microstrip Transmission line On HFSS , all reports S parameters , impedance ,...
PPT
PPT
Matlab day 1: Introduction to MATLAB
PPTX
sheet resistivity
Matlab-free course by Mohd Esa
Numerical Computing
Matlab basic and image
Signal & systems
Principle and working of a semiconductor laser
Matlab ppt
Simulation of Wireless Communication Systems
Introduction to matlab lecture 1 of 4
Ic voltage regulators
Lecture 1 introduction to communication systems
Introduction to matlab
Matlab Tutorial.ppt
Inroduction to HFSS
Probability Density Function (PDF)
Matching techniques
Amplitude Modulation using Multipliers and Envelope Detector
Microstrip Transmission line On HFSS , all reports S parameters , impedance ,...
Matlab day 1: Introduction to MATLAB
sheet resistivity
Ad

Similar to User defined functions in matlab (20)

PDF
Matlab functions
PPTX
Lecture_5_-_Functions_in_C_Detailed.pptx
PPTX
Functions in Python Programming Language
PPTX
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
PPTX
Unit-III.pptx
PDF
Functions-Computer programming
PPT
Basic information of function in cpu
DOC
Functions
PPTX
functions.pptx
PPTX
OOPS Object oriented Programming PPT Tutorial
PPTX
Functions in python
PDF
[ITP - Lecture 12] Functions in C/C++
PPTX
JNTUK python programming python unit 3.pptx
DOC
c.p function
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
Functions and Modules.pptx
PPT
Ch4 functions
PDF
cp Module4(1)
PPTX
Python Functions.pptx
Matlab functions
Lecture_5_-_Functions_in_C_Detailed.pptx
Functions in Python Programming Language
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
Unit-III.pptx
Functions-Computer programming
Basic information of function in cpu
Functions
functions.pptx
OOPS Object oriented Programming PPT Tutorial
Functions in python
[ITP - Lecture 12] Functions in C/C++
JNTUK python programming python unit 3.pptx
c.p function
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
Functions and Modules.pptx
Ch4 functions
cp Module4(1)
Python Functions.pptx
Ad

More from Infinity Tech Solutions (20)

PDF
Database management system session 6
PDF
Database management system session 5
PDF
Database Management System-session 3-4-5
PDF
Database Management System-session1-2
PDF
Main topic 3 problem solving and office automation
PDF
Introduction to c programming
PDF
PDF
Bds session 13 14
PDF
Computer memory, Types of programming languages
PDF
Basic hardware familiarization
PDF
Programming with matlab session 6
PDF
Programming with matlab session 3 notes
PPTX
AI/ML/DL/BCT A Revolution in Maritime Sector
PDF
Programming with matlab session 5 looping
PDF
BIG DATA Session 7 8
PDF
BIG DATA Session 6
PDF
Database management system session 6
Database management system session 5
Database Management System-session 3-4-5
Database Management System-session1-2
Main topic 3 problem solving and office automation
Introduction to c programming
Bds session 13 14
Computer memory, Types of programming languages
Basic hardware familiarization
Programming with matlab session 6
Programming with matlab session 3 notes
AI/ML/DL/BCT A Revolution in Maritime Sector
Programming with matlab session 5 looping
BIG DATA Session 7 8
BIG DATA Session 6

Recently uploaded (20)

PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Well-logging-methods_new................
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
PPT on Performance Review to get promotions
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Sustainable Sites - Green Building Construction
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
DOCX
573137875-Attendance-Management-System-original
PPT
Project quality management in manufacturing
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Welding lecture in detail for understanding
PPTX
Internet of Things (IOT) - A guide to understanding
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Well-logging-methods_new................
Lesson 3_Tessellation.pptx finite Mathematics
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
CYBER-CRIMES AND SECURITY A guide to understanding
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPT on Performance Review to get promotions
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Sustainable Sites - Green Building Construction
Model Code of Practice - Construction Work - 21102022 .pdf
Arduino robotics embedded978-1-4302-3184-4.pdf
573137875-Attendance-Management-System-original
Project quality management in manufacturing
Lecture Notes Electrical Wiring System Components
Structs to JSON How Go Powers REST APIs.pdf
Operating System & Kernel Study Guide-1 - converted.pdf
Welding lecture in detail for understanding
Internet of Things (IOT) - A guide to understanding

User defined functions in matlab

  • 1. SESSION-7-8 User Defined Functions in MATLAB By: Prof. Ganesh Ingle
  • 2. Course Main Topic/Chapters Introduction User Defined Functions in MATLAB Categories of Functions Summary
  • 3. User Defined Functions in MATLAB Function: A function is a block of code that performs a specific task. MATLAB allows you to define functions according to your need. These functions are known as user-defined functions. Advantages : 1. The subprogram are easier to write, understand and debug. 2. A function can call itself again. It is called a recursive function. Many calculations can be done easily by using recursive functions such as calculation of factorial of a number, etc. 3. Reduction in size of program due to program code of a function can be used again and again, by calling it. 4. The complexity of the entire program can be divided into simple subtask and then function subprograms can be written for each subtask. 5. A library of a function can be designed and tested for use of every programmer. 6. Code reusability
  • 4. User Defined Functions in MATLAB Function: A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate files. The name of the file and of the function should be the same. Functions operate on variables within their own workspace, which is also called the local workspace, separate from the workspace you access at the MATLAB command prompt which is called the base workspace. Functions can accept more than one input arguments and may return more than one output arguments. Syntax of a function statement is − function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)
  • 5. Types of Functions Functions Predefined Functions Library Functions Declared in header file Body in .dll files User Defined Functions Anonymous Functions Primary and Sub-Functions Nested Functions Recursive Functions Private Functions
  • 6. Types of Arguments Basically, there are two types of arguments: 1.Actual arguments: The variables declared in the function prototype or definition are known as Formal arguments 2.Formal arguments : The variable that are passed to the called function from the main function are known as Actual arguments. 3.Local Variable A local variable is a type of variable declared within programming block or subroutines. It can only be used only inside that subroutine or code block in which they were declared. The local variable exists until the block of the function is in under execution. After that, it will be destroyed automatically. 4.Global variables: Global variables are defined outside of a subroutine or function. The global variable will hold its value throughout the lifetime of a program. They can be accessed within any function defined for the program.
  • 7. Types of Arguments Basically, there are two types of arguments: 1.Actual arguments: The variables declared in the function prototype or definition are known as Formal arguments 2.Formal arguments : The variable that are passed to the called function from the main function are known as Actual arguments. 3.Local Variable A local variable is a type of variable declared within programming block or subroutines. It can only be used only inside that subroutine or code block in which they were declared. The local variable exists until the block of the function is in under execution. After that, it will be destroyed automatically. 4.Global variables: Global variables are defined outside of a subroutine or function. The global variable will hold its value throughout the lifetime of a program. They can be accessed within any function defined for the program.
  • 8. Global Variables Global variables can be shared by more than one function. For this, you need to declare the variable as global in all the functions.I f you want to access that variable from the base workspace, then declare the variable at the command line. The global declaration must occur before the variable is actually used in a function. It is a good practice to use capital letters for the names of global variables to distinguish them from other variables. Example Let us create a function file named average.m and type the following code in it − function avg = average(nums) global TOTAL avg = sum(nums)/TOTAL; end Create a script file and type the following code in it − global TOTAL; TOTAL = 10; n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42]; av = average(n) When you run the file, it will display the following result − av = 35.500
  • 9. Example Example The following function named mymax should be written in a file named mymax.m. It takes five numbers as argument and returns the maximum of the numbers. function max = mymax(n1, n2, n3, n4, n5) %This function calculates the maximum of the five numbers given as input max = n1; if(n2 > max) max = n2; end if(n3 > max) max = n3; end if(n4 > max) max = n4; end if(n5 > max) max = n5; end You can call the function as − mymax(34, 78, 89, 23, 11)
  • 10. Anonymous Functions An anonymous function is like an inline function in traditional programming languages, defined within a single MATLAB statement. It consists of a single MATLAB expression and any number of input and output arguments. You can define an anonymous function right at the MATLAB command line or within a function or script. This way you can create simple functions without having to create a file for them. The syntax for creating an anonymous function from an expression is f = @(arglist)expression Example In this example, we will write an anonymous function named power, which will take two numbers as input and return first number raised to the power of the second number. Create a script file and type the following code in it − power = @(x, n) x.^n; result1 = power(7, 3) result2 = power(49, 0.5) result3 = power(10, -10) result4 = power (4.5, 1.5) When you run the file, it displays − result1 = 343 result2 = 7 result3 = 1.0000e-10 result4 = 9.5459
  • 11. Primary and Sub-Functions Any function other than an anonymous function must be defined within a file. Each function file contains a required primary function that appears first and any number of optional sub-functions that comes after the primary function and used by it. Primary functions can be called from outside of the file that defines them, either from command line or from other functions, but sub-functions cannot be called from command line or other functions, outside the function file. Sub-functions are visible only to the primary function and other sub-functions within the function file that defines them. Example Let us write a function named quadratic that would calculate the roots of a quadratic equation. The function would take three inputs, the quadratic co- efficient, the linear co-efficient and the constant term. It would return the roots.The function file quadratic.m will contain the primary function quadratic and the sub-function disc, which calculates the discriminant.
  • 12. Primary and Sub-Functions Create a function file quadratic.m and type the following code in it − function [x1,x2] = quadratic(a,b,c) %this function returns the roots of % a quadratic equation. % It takes 3 input arguments % which are the co-efficients of x2, x and the %constant term % It returns the roots d = disc(a,b,c); x1 = (-b + d) / (2*a); x2 = (-b - d) / (2*a); end % end of quadratic function dis = disc(a,b,c) %function calculates the discriminant dis = sqrt(b^2 - 4*a*c); end % end of sub-function You can call the above function from command prompt as − quadratic(2,4,-4) MATLAB will execute the above statement and return the following result − ans = 0.7321
  • 13. Nested Functions You can define functions within the body of another function. These are called nested functions. A nested function contains any or all of the components of any other function. Nested functions are defined within the scope of another function and they share access to the containing function's workspace. A nested function follows the following syntax − function x = A(p1, p2) ... B(p2) function y = B(p3) ... end ... end
  • 14. Nested Functions Example Let us rewrite the function quadratic, from previous example, however, this time the disc function will be a nested function. Create a function file quadratic2.m and type the following code in it − function [x1,x2] = quadratic2(a,b,c) function disc % nested function d = sqrt(b^2 - 4*a*c); end % end of function disc disc; x1 = (-b + d) / (2*a); x2 = (-b - d) / (2*a); end % end of function quadratic2 You can call the above function from command prompt as − quadratic2(2,4,-4) MATLAB will execute the above statement and return the following result − ans = 0.73205
  • 15. Private Functions A private function is a primary function that is visible only to a limited group of other functions. If you do not want to expose the implementation of a function(s), you can create them as private functions. Private functions reside in subfolders with the special name private. They are visible only to functions in the parent folder. Example Let us rewrite the quadratic function. This time, however, the disc function calculating the discriminant, will be a private function. Create a subfolder named private in working directory. Store the following function file disc.m in it − function dis = disc(a,b,c) %function calculates the discriminant dis = sqrt(b^2 - 4*a*c); end % end of sub-function
  • 16. Private Functions Create a function quadratic3.m in your working directory and type the following code in it − function [x1,x2] = quadratic3(a,b,c) %this function returns the roots of % a quadratic equation. % It takes 3 input arguments % which are the co-efficient of x2, x and the constant term % It returns the roots d = disc(a,b,c); x1 = (-b + d) / (2*a); x2 = (-b - d) / (2*a); end % end of quadratic3 You can call the above function from command prompt as − quadratic3(2,4,-4) MATLAB will execute the above statement and return the following result − ans = 0.73205