SlideShare una empresa de Scribd logo
1 de 5
Descargar para leer sin conexión
http://www.tutorialspoint.com/matlab/matlab_functions.htm Copyright © tutorialspoint.com
MATLAB - FUNCTIONS
A functionis a group of statements that together performa task. InMATLAB, functions are defined inseparate
files. The name of the file and of the functionshould be the same.
Functions operate onvariables withintheir ownworkspace, whichis also called the local workspace, separate
fromthe workspace youaccess at the MATLAB command prompt whichis called the base workspace.
Functions canaccept more thanone input arguments and may returnmore thanone output arguments
Syntax of a functionstatement is:
function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)
Example
The following functionnamed mymax should be writtenina file named mymax.m. It takes five numbers as
argument and returns the maximumof the numbers.
Create a functionfile, named mymax.mand type the following code init:
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
The first line of a functionstarts withthe keyword function. It gives the name of the functionand order of
arguments. Inour example, the mymax functionhas five input arguments and one output argument.
The comment lines that come right after the functionstatement provide the help text. These lines are printed
whenyoutype:
help mymax
MATLAB willexecute the above statement and returnthe following result:
This function calculates the maximum of the
five numbers given as input
Youcancallthe functionas:
mymax(34, 78, 89, 23, 11)
MATLAB willexecute the above statement and returnthe following result:
ans =
89
Anonymous Functions
Anonymous Functions
Ananonymous functionis like aninline functionintraditionalprogramming languages, defined withina single
MATLAB statement. It consists of a single MATLAB expressionand any number of input and output arguments.
Youcandefine ananonymous functionright at the MATLAB command line or withina functionor script.
This way youcancreate simple functions without having to create a file for them.
The syntax for creating ananonymous functionfromanexpressionis
f = @(arglist)expression
Example
Inthis example, we willwrite ananonymous functionnamed power, whichwilltake two numbers as input and
returnfirst number raised to the power of the second number.
Create a script file and type the following code init:
power = @(x, n) x.^n;
result1 = power(7, 3)
result2 = power(49, 0.5)
result3 = power(10, -10)
result4 = power (4.5, 1.5)
Whenyourunthe file, it displays:
result1 =
343
result2 =
7
result3 =
1.0000e-10
result4 =
9.5459
Primary and Sub-Functions
Any functionother thanananonymous functionmust be defined withina file. Eachfunctionfile contains a required
primary functionthat appears first and any number of optionalsub-functions that comes after the primary function
and used by it.
Primary functions canbe called fromoutside of the file that defines them, either fromcommand line or fromother
functions, but sub-functions cannot be called fromcommand line or other functions, outside the functionfile.
Sub-functions are visible only to the primary functionand other sub-functions withinthe functionfile that defines
them.
Example
Let us write a functionnamed quadratic that would calculate the roots of a quadratic equation. The functionwould
take three inputs, the quadratic co-efficient, the linear co-efficient and the constant term. It would returnthe
roots.
The functionfile quadratic.mwillcontainthe primary functionquadratic and the sub-functiondisc, whichcalculates
the discriminant.
Create a functionfile quadratic.m and type the following code init:
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
Youcancallthe above functionfromcommand prompt as:
quadratic(2,4,-4)
MATLAB willexecute the above statement and returnthe following result:
ans =
0.7321
Nested Functions
Youcandefine functions withinthe body of another function. These are called nested functions. A nested function
contains any or allof the components of any other function.
Nested functions are defined withinthe scope of another functionand they share access to the containing
function's workspace.
A nested functionfollows the following syntax:
function x = A(p1, p2)
...
B(p2)
function y = B(p3)
...
end
...
end
Example
Let us rewrite the functionquadratic, fromprevious example, however, this time the disc functionwillbe a nested
function.
Create a functionfile quadratic2.m and type the following code init:
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
Youcancallthe above functionfromcommand prompt as:
quadratic2(2,4,-4)
MATLAB willexecute the above statement and returnthe following result:
ans =
0.7321
Private Functions
A private functionis a primary functionthat is visible only to a limited group of other functions. If youdo not want to
expose the implementationof a function(s), youcancreate themas private functions.
Private functions reside insubfolders withthe specialname private.
They are visible only to functions inthe parent folder.
Example
Let us rewrite the quadratic function. This time, however, the disc functioncalculating the discriminant, willbe a
private function.
Create a subfolder named private inworking directory. Store the following functionfile disc.m init:
function dis = disc(a,b,c)
%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function
Create a functionquadratic3.minyour working directory and type the following code init:
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-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 quadratic3
Youcancallthe above functionfromcommand prompt as:
quadratic3(2,4,-4)
MATLAB willexecute the above statement and returnthe following result:
ans =
0.7321
Global Variables
Globalvariables canbe shared by more thanone function. For this, youneed to declare the variable as globalin
allthe functions.
If youwant to access that variable fromthe base workspace, thendeclare the variable at the command line.
The globaldeclarationmust occur before the variable is actually used ina function. It is a good practice to use
capitalletters for the names of globalvariables to distinguishthemfromother variables.
Example
Let us create a functionfile named average.mand type the following code init:
function avg = average(nums)
global TOTAL
avg = sum(nums)/TOTAL;
end
Create a script file and type the following code init:
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
Whenyourunthe file, it willdisplay the following result:
av =
35.5000

Más contenido relacionado

La actualidad más candente

Scala user-group-19.03.2014
Scala user-group-19.03.2014Scala user-group-19.03.2014
Scala user-group-19.03.2014Jan Herich
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materialsgayaramesh
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationMoniruzzaman _
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationProf Ansari
 
Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5Kumar
 
INTRODUCTION TO MATLAB session with notes
  INTRODUCTION TO MATLAB   session with  notes  INTRODUCTION TO MATLAB   session with  notes
INTRODUCTION TO MATLAB session with notesInfinity Tech Solutions
 
Recursion(Advanced data structure)
Recursion(Advanced data structure)Recursion(Advanced data structure)
Recursion(Advanced data structure)kurubameena1
 
Linked lists in Data Structure
Linked lists in Data StructureLinked lists in Data Structure
Linked lists in Data StructureMuhazzab Chouhadry
 
Doubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsDoubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsShubham Sharma
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Adam Mukharil Bachtiar
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
 
Data Structure Lecture 6
Data Structure Lecture 6Data Structure Lecture 6
Data Structure Lecture 6Teksify
 

La actualidad más candente (20)

Scala user-group-19.03.2014
Scala user-group-19.03.2014Scala user-group-19.03.2014
Scala user-group-19.03.2014
 
R: Apply Functions
R: Apply FunctionsR: Apply Functions
R: Apply Functions
 
R programming Language
R programming LanguageR programming Language
R programming Language
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materials
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Link List
Link ListLink List
Link List
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory Allocation
 
Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Linked list
Linked listLinked list
Linked list
 
INTRODUCTION TO MATLAB session with notes
  INTRODUCTION TO MATLAB   session with  notes  INTRODUCTION TO MATLAB   session with  notes
INTRODUCTION TO MATLAB session with notes
 
Recursion(Advanced data structure)
Recursion(Advanced data structure)Recursion(Advanced data structure)
Recursion(Advanced data structure)
 
Linked lists in Data Structure
Linked lists in Data StructureLinked lists in Data Structure
Linked lists in Data Structure
 
Doubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsDoubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || Algorithms
 
Data Structure (Double Linked List)
Data Structure (Double Linked List)Data Structure (Double Linked List)
Data Structure (Double Linked List)
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Data Structure Lecture 6
Data Structure Lecture 6Data Structure Lecture 6
Data Structure Lecture 6
 

Destacado

Logistic Regression, Linear and Quadratic Discriminant Analysis and K-Nearest...
Logistic Regression, Linear and Quadratic Discriminant Analysis and K-Nearest...Logistic Regression, Linear and Quadratic Discriminant Analysis and K-Nearest...
Logistic Regression, Linear and Quadratic Discriminant Analysis and K-Nearest...Tarek Dib
 
Discriminant analysis
Discriminant analysisDiscriminant analysis
Discriminant analysisBhasker Rajan
 
Pattern Recognition: Class mean classifier
Pattern Recognition: Class mean classifierPattern Recognition: Class mean classifier
Pattern Recognition: Class mean classifierMd Mamunur Rashid
 
Topic Models - LDA and Correlated Topic Models
Topic Models - LDA and Correlated Topic ModelsTopic Models - LDA and Correlated Topic Models
Topic Models - LDA and Correlated Topic ModelsClaudia Wagner
 
LDA presentation
LDA presentationLDA presentation
LDA presentationMohit Gupta
 
discriminant analysis
discriminant analysisdiscriminant analysis
discriminant analysiskrishnadk
 
Discriminant analysis
Discriminant analysisDiscriminant analysis
Discriminant analysisMurali Raj
 
Dabur Strategy
Dabur StrategyDabur Strategy
Dabur StrategyMurali Raj
 

Destacado (13)

Logistic Regression, Linear and Quadratic Discriminant Analysis and K-Nearest...
Logistic Regression, Linear and Quadratic Discriminant Analysis and K-Nearest...Logistic Regression, Linear and Quadratic Discriminant Analysis and K-Nearest...
Logistic Regression, Linear and Quadratic Discriminant Analysis and K-Nearest...
 
Discriminant analysis
Discriminant analysisDiscriminant analysis
Discriminant analysis
 
Pattern Recognition: Class mean classifier
Pattern Recognition: Class mean classifierPattern Recognition: Class mean classifier
Pattern Recognition: Class mean classifier
 
Topic Models - LDA and Correlated Topic Models
Topic Models - LDA and Correlated Topic ModelsTopic Models - LDA and Correlated Topic Models
Topic Models - LDA and Correlated Topic Models
 
LDA presentation
LDA presentationLDA presentation
LDA presentation
 
Discriminant analysis
Discriminant analysisDiscriminant analysis
Discriminant analysis
 
CSC446: Pattern Recognition (LN5)
CSC446: Pattern Recognition (LN5)CSC446: Pattern Recognition (LN5)
CSC446: Pattern Recognition (LN5)
 
discriminant analysis
discriminant analysisdiscriminant analysis
discriminant analysis
 
Discriminant analysis
Discriminant analysisDiscriminant analysis
Discriminant analysis
 
Discriminant analysis
Discriminant analysisDiscriminant analysis
Discriminant analysis
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
 
Discriminant analysis
Discriminant analysisDiscriminant analysis
Discriminant analysis
 
Dabur Strategy
Dabur StrategyDabur Strategy
Dabur Strategy
 

Similar a MATLAB Functions Guide

Similar a MATLAB Functions Guide (20)

User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
 
Tutorial2
Tutorial2Tutorial2
Tutorial2
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
 
Matlab ch1 intro
Matlab ch1 introMatlab ch1 intro
Matlab ch1 intro
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make
 
Basics of MATLAB programming
Basics of MATLAB programmingBasics of MATLAB programming
Basics of MATLAB programming
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Matlab Manual
Matlab ManualMatlab Manual
Matlab Manual
 
Python advance
Python advancePython advance
Python advance
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 

Más de pramodkumar1804 (20)

Matlab syntax
Matlab syntaxMatlab syntax
Matlab syntax
 
Matlab strings
Matlab stringsMatlab strings
Matlab strings
 
Matlab simulink
Matlab simulinkMatlab simulink
Matlab simulink
 
Matlab polynomials
Matlab polynomialsMatlab polynomials
Matlab polynomials
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
 
Matlab overview 3
Matlab overview 3Matlab overview 3
Matlab overview 3
 
Matlab overview 2
Matlab overview 2Matlab overview 2
Matlab overview 2
 
Matlab overview
Matlab overviewMatlab overview
Matlab overview
 
Matlab operators
Matlab operatorsMatlab operators
Matlab operators
 
Matlab variables
Matlab variablesMatlab variables
Matlab variables
 
Matlab numbers
Matlab numbersMatlab numbers
Matlab numbers
 
Matlab matrics
Matlab matricsMatlab matrics
Matlab matrics
 
Matlab m files
Matlab m filesMatlab m files
Matlab m files
 
Matlab loops 2
Matlab loops 2Matlab loops 2
Matlab loops 2
 
Matlab loops
Matlab loopsMatlab loops
Matlab loops
 
Matlab integration
Matlab integrationMatlab integration
Matlab integration
 
Matlab graphics
Matlab graphicsMatlab graphics
Matlab graphics
 
Matlab gnu octave
Matlab gnu octaveMatlab gnu octave
Matlab gnu octave
 
Matlab operators
Matlab operatorsMatlab operators
Matlab operators
 
Matlab differential
Matlab differentialMatlab differential
Matlab differential
 

Último

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
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
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 

Último (20)

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
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
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
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 

MATLAB Functions Guide

  • 1. http://www.tutorialspoint.com/matlab/matlab_functions.htm Copyright © tutorialspoint.com MATLAB - FUNCTIONS A functionis a group of statements that together performa task. InMATLAB, functions are defined inseparate files. The name of the file and of the functionshould be the same. Functions operate onvariables withintheir ownworkspace, whichis also called the local workspace, separate fromthe workspace youaccess at the MATLAB command prompt whichis called the base workspace. Functions canaccept more thanone input arguments and may returnmore thanone output arguments Syntax of a functionstatement is: function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN) Example The following functionnamed mymax should be writtenina file named mymax.m. It takes five numbers as argument and returns the maximumof the numbers. Create a functionfile, named mymax.mand type the following code init: 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 The first line of a functionstarts withthe keyword function. It gives the name of the functionand order of arguments. Inour example, the mymax functionhas five input arguments and one output argument. The comment lines that come right after the functionstatement provide the help text. These lines are printed whenyoutype: help mymax MATLAB willexecute the above statement and returnthe following result: This function calculates the maximum of the five numbers given as input Youcancallthe functionas: mymax(34, 78, 89, 23, 11) MATLAB willexecute the above statement and returnthe following result: ans = 89 Anonymous Functions
  • 2. Anonymous Functions Ananonymous functionis like aninline functionintraditionalprogramming languages, defined withina single MATLAB statement. It consists of a single MATLAB expressionand any number of input and output arguments. Youcandefine ananonymous functionright at the MATLAB command line or withina functionor script. This way youcancreate simple functions without having to create a file for them. The syntax for creating ananonymous functionfromanexpressionis f = @(arglist)expression Example Inthis example, we willwrite ananonymous functionnamed power, whichwilltake two numbers as input and returnfirst number raised to the power of the second number. Create a script file and type the following code init: power = @(x, n) x.^n; result1 = power(7, 3) result2 = power(49, 0.5) result3 = power(10, -10) result4 = power (4.5, 1.5) Whenyourunthe file, it displays: result1 = 343 result2 = 7 result3 = 1.0000e-10 result4 = 9.5459 Primary and Sub-Functions Any functionother thanananonymous functionmust be defined withina file. Eachfunctionfile contains a required primary functionthat appears first and any number of optionalsub-functions that comes after the primary function and used by it. Primary functions canbe called fromoutside of the file that defines them, either fromcommand line or fromother functions, but sub-functions cannot be called fromcommand line or other functions, outside the functionfile. Sub-functions are visible only to the primary functionand other sub-functions withinthe functionfile that defines them. Example Let us write a functionnamed quadratic that would calculate the roots of a quadratic equation. The functionwould take three inputs, the quadratic co-efficient, the linear co-efficient and the constant term. It would returnthe roots. The functionfile quadratic.mwillcontainthe primary functionquadratic and the sub-functiondisc, whichcalculates the discriminant. Create a functionfile quadratic.m and type the following code init: 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
  • 3. 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 Youcancallthe above functionfromcommand prompt as: quadratic(2,4,-4) MATLAB willexecute the above statement and returnthe following result: ans = 0.7321 Nested Functions Youcandefine functions withinthe body of another function. These are called nested functions. A nested function contains any or allof the components of any other function. Nested functions are defined withinthe scope of another functionand they share access to the containing function's workspace. A nested functionfollows the following syntax: function x = A(p1, p2) ... B(p2) function y = B(p3) ... end ... end Example Let us rewrite the functionquadratic, fromprevious example, however, this time the disc functionwillbe a nested function. Create a functionfile quadratic2.m and type the following code init: 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 Youcancallthe above functionfromcommand prompt as: quadratic2(2,4,-4) MATLAB willexecute the above statement and returnthe following result: ans = 0.7321 Private Functions
  • 4. A private functionis a primary functionthat is visible only to a limited group of other functions. If youdo not want to expose the implementationof a function(s), youcancreate themas private functions. Private functions reside insubfolders withthe specialname private. They are visible only to functions inthe parent folder. Example Let us rewrite the quadratic function. This time, however, the disc functioncalculating the discriminant, willbe a private function. Create a subfolder named private inworking directory. Store the following functionfile disc.m init: function dis = disc(a,b,c) %function calculates the discriminant dis = sqrt(b^2 - 4*a*c); end % end of sub-function Create a functionquadratic3.minyour working directory and type the following code init: 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-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 quadratic3 Youcancallthe above functionfromcommand prompt as: quadratic3(2,4,-4) MATLAB willexecute the above statement and returnthe following result: ans = 0.7321 Global Variables Globalvariables canbe shared by more thanone function. For this, youneed to declare the variable as globalin allthe functions. If youwant to access that variable fromthe base workspace, thendeclare the variable at the command line. The globaldeclarationmust occur before the variable is actually used ina function. It is a good practice to use capitalletters for the names of globalvariables to distinguishthemfromother variables. Example Let us create a functionfile named average.mand type the following code init: function avg = average(nums) global TOTAL avg = sum(nums)/TOTAL; end Create a script file and type the following code init: global TOTAL;
  • 5. TOTAL = 10; n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42]; av = average(n) Whenyourunthe file, it willdisplay the following result: av = 35.5000