0% found this document useful (0 votes)
110 views8 pages

Introduction To Functions in Matlab: Syntax

Functions in MATLAB operate within their own local workspace separately from the base workspace. Functions can accept multiple input arguments and return multiple output arguments. Functions are defined with a function declaration statement that specifies the inputs, outputs, and function name. Functions can be saved in their own files or within scripts. Nested and private functions can also be created. Global variables can be shared between functions by declaring them globally.

Uploaded by

saran gul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views8 pages

Introduction To Functions in Matlab: Syntax

Functions in MATLAB operate within their own local workspace separately from the base workspace. Functions can accept multiple input arguments and return multiple output arguments. Functions are defined with a function declaration statement that specifies the inputs, outputs, and function name. Functions can be saved in their own files or within scripts. Nested and private functions can also be created. Global variables can be shared between functions by declaring them globally.

Uploaded by

saran gul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Signals and Systems Lab DEE, FURC

Introduction to Functions in Matlab


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
function [y1,...,yN] = myfun(x1,...,xM)
Description
function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that accepts
inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first
executable line of the function. Valid function names begin with an alphabetic character, and can
contain letters, numbers, or underscores.
You can save your function:
 In a function file which contains only function
definitions. The name of the file should match the name
of the first function in the file.
 In a script file which contains commands and function
definitions. Functions must be at the end of the file.
Script files cannot have the same name as a function in
the file. Functions are supported in scripts in R2016b or
later.
Files can include multiple local functions or nested functions. For readability, use
the end keyword to indicate the end of each function in a file. The end keyword is required
when:
 Any function in the file contains a nested function.
 The function is a local function within a function file,
and any local function in the file uses the end keyword.
 The function is a local function within a script file.

1
Signals and Systems Lab DEE, FURC

Examples
Function with One Output
Define a function in a file named average.m that accepts an input vector, calculates the average
of the values, and returns a single result.
function y = average(x)
if ~isvector(x)
error('Input must be a vector')
end
y = sum(x)/length(x);
end
Call the function from the command line.
z = 1:99;
average(z)
ans =
50
Function in a Script File

Define a script in a file named integrationScript.m that computes the value of the integrand


at   and computes the area under the curve from 0 to  . Include a local function that defines
the integrand,  .
% Compute the value of the integrand at 2*pi/3.
x = 2*pi/3;
y = myIntegrand(x)

% Compute the area under the curve from 0 to pi.


xmin = 0;
xmax = pi;
f = @myIntegrand;
a = integral(f,xmin,xmax)

function y = myIntegrand(x)
y = sin(x).^3;
end
y=

0.6495

a=

1.3333

2
Signals and Systems Lab DEE, FURC

Function with Multiple Outputs


Define a function in a file named stat.m that returns the mean and standard deviation of an input
vector.
function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end
Call the function from the command line.
values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat(values)
ave =
47.3400
stdev =
29.4124
Multiple Functions in a Function File
Define two functions in a file named stat2.m, where the first function calls the second.
function [m,s] = stat2(x)
n = length(x);
m = avg(x,n);
s = sqrt(sum((x-m).^2/n));
end

function m = avg(x,n)
m = sum(x)/n;
end
Function avg is a local function. Local functions are only available to other functions within the
same file.
Call function stat2 from the command line.
values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat2(values)
ave =
47.3400
stdev =
29.4124

More Examples
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.

3
Signals and Systems Lab DEE, FURC

Create a function file, named mymax.m and type the following code in it −

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 function starts with the keyword function. It gives the name of the function
and order of arguments. In our example, the mymax function has five input arguments and one
output argument.

The comment lines that come right after the function statement provide the help text. These
lines are printed when you type −

help mymax
MATLAB will execute the above statement and return the following result −

4
Signals and Systems Lab DEE, FURC

This function calculates the maximum of the


five numbers given as input
You can call the function as −

mymax(34, 78, 89, 23, 11)

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

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);

5
Signals and Systems Lab DEE, FURC

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

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

6
Signals and Systems Lab DEE, FURC

% 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

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.

If 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

7
Signals and Systems Lab DEE, FURC

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy