Sei sulla pagina 1di 7

Functions in MATLAB

Lab 4

1 ECE 201 Lab- Summer 2010


What is a function?
 A subroutine which is ‘defined’ and saved as a file and
then can be ‘called’ by other scripts, or from the
command prompt

 Advantages
 Repeatable operations can be written as a functions
 The actual code becomes much cleaner

2 ECE 201 Lab- Summer 2010


A function is also an m-file
 Basic structure of a function
function [output variables] = functionname (input variables)

% Comments for the help file

check for errors in input variables

commands to find the output variable

 You do not need to return the output variables – just ensure that the
variable names are same
 The name of the m-file should be the same as the function name you have
given

3 ECE 201 Lab- Summer 2010


An example – adding two numbers
function [c] = add(a,b)

% The purpose of this function is to add 2 positive numbers and


return the result.
% Syntax : c = add(a,b)
% where both a and b should be greater than 0.

if (a<0 || b<0)
error (‘The inputs are not positive’);
end

c = a + b;

 Calling the function (either in command prompt, or in another m-file)

c = add(5,4);

4 ECE 201 Lab- Summer 2010


Example : Multiple output variables
function [c, d] = add_diff(a,b)

% The purpose of this function is to add and subtract 2 positive


numbers and return the both the results.
% Syntax : [c, d] = add(a,b)
% where both a and b should be greater than 0.

if (a<0 || b<0)
error (‘The inputs are not positive’);
end

c = a + b;
d = a – b;

 Calling the function (either in command prompt, or in another m-file)

[c, d] = add_diff(5,4);

5 ECE 201 Lab- Summer 2010


Example : Working with vectors
function [yy] = multiply(xx,x1,x2)

% The purpose of this function is to accept a vector as an input,


multiply it with a linear vector and output the result
% Syntax : yy = multiply(xx,x1,x2)
% where both xx is a vector, x1 and x2 are start and end
of the linear vector.

if (x2<x1)
error (‘The end is less than the start’);
end

N = length(xx);
xx_temp = linspace(x1,x2,N);
yy = xx.*xx_temp;

6 ECE 201 Lab- Summer 2010


Things to remember…
 In most cases a function will never have an input
command, only input variables
 A function will never be ‘run’. It will only be ‘called’
 The ‘call’ command and the ‘function definition’ line
should be same. Always check the sequence of output and
input variables
 Always save the function m-file with the same name as
the function
 The function m-file should be saved in the current
directory

7 ECE 201 Lab- Summer 2010

Potrebbero piacerti anche