Sei sulla pagina 1di 14

Lecture 7

Functions

Learning Outcome

Understand scripts and functions in


Matlab
Understand global variables
Get to know the built-in functions in
Matlab

Introduction
In Matlab programming, we need to reuse some
parts of the codes in many situations.
In last lecture we learnt for and while loops, which
enabled us to repeat some code blocks
There is another mechanism called function in
Matlab, which enables us to package some code
segments into a block and give the block a name.
Whenever we want to carry out the operations in the
block, we just need to call the block name and pass
some necessary parameters to it.

Introduction
Advantages of using functions:
Code segments in functions can be re-used in
other Matlab programs
Code segments in functions can be tested and
verified separately

Introduction
Previously we have learnt and used a number of
Matlab functions without realising it.
Matlab functions
min, max, sin, exp, rand
For Maths operation
For data plotting

plot, surf, contour

For input/output
For string processing

input, fprintf, fopen, fclose

sprintf, int2num

To define functions in Matlab


All programs within MATLAB are m-files, with the

extension name .m. An m-files can be a script or a


function.
To define a function, create a m-file, and give it the
same name you use to call the function. In this m-file,
start the main part by defining the function using the
following format. Include some comment lines to help
readers understanding the code.
Format:
function [out1, out2, ...] = funname(in1, in2, ...)
Function
declaration

List of return
values

Function
name

List of input
values

Example: defining a function


% --- Main program: m1.m --% This script calls the function fsum to add two numbers.
% ----------------------------------------------------------a = 5;
b=4;
c = fsum(a,b);
fprintf(%d = %d + %d\n, c, a, b);
function ov = fsum(ia, ib)
% --- fsum.m --% This functions accepts two arguments, and returns
% their summation.
ov = ia+ib;

Note: the function definition file fsum.m should be in the


same directory as the main program m1.m, or in a directory
defined by the path variable in Matlab.

Scripts and functions


A function cannot directly access any
variables in the workspace. It receives input
information through input arguments and
exports output information through output
arguments

Scripts and functions

We will generate Pascals triangle for a given


integer dimension, n.
e.g. for n = 6
1
1

1
P
1
1

1 1
5

3 6 10

4 10

1
2

1
3

1
4

Pi, j Pi 1, j Pi, j 1

Each entry is the sum of the entry immediately to


the left and the entry immediately above.

Script example
%
%
%
%
%

--- Pascal_Script --This script generates a matrix, P, containing Pascals


triangle of a given dimension.
Note that the integer, n, is assumed to be defined already.
-----------------------------------------------------------

clear all; clc;


n=6;
disp(['Pascal''s triangle of dimension ' num2str(n)]);
P = zeros(n,n);
% Initialise P as a matrix of zeros.
P(1,:)=ones(1,n); % Set all entries in row 1 equal to 1.
P(:,1)=ones(n,1); % Set all entries in column 1 equal to 1.
for irow=2:(n-1) % Step through rows 2 up to (n-1)
for jcol=2:(n+1-irow)
% Columns 2 up to (n+1-irow)
P(irow,jcol)= P(irow-1,jcol) + P(irow,jcol-1);
end
end
P

Function example
function PascTria = fPascal( np );
% --- fPascal --%
% PascTria = fPascal( np );
% This function computes Pascals triangle of a given
% dimension, <np>.
% ----------------------------------------------------------disp(['Pascal''s triangle of dimension ' num2str(np)]);
Z = zeros(np,np);
% Initialise Z as a matrix of zeros.
Z(1,:)=ones(1,np); % Set all entries in row 1 equal to 1.
Z(:,1)=ones(np,1); % Set all entries in column 1 equal to 1.
for irow=2:(np-1) % Step through rows 2 up to (np-1)
for jcol=2:(np+1-irow)
% Columns 2 up to (np+1-irow)
Z(irow,jcol)= Z(irow-1,jcol) + Z(irow,jcol-1);
end
end
PascTria = Z;

Functions

Now we investigate a few features of function

>> fPascal
>>
>>
>>
>>

<RET>

n=7; Z = 11;
fPascal(n)
Z
PascTria

% This will produce an error!


<RET>
<RET>
<RET>
<RET>

Notice how the input argument (n) does not need to have
the same name as that within the function (np) in effect,
np is a copy of the variable n which will be used internally
within the function.
The output matrix has not been assigned to any variable so
it is automatically assigned to ans. Therefore Z is still 11
and PascTria is undefined.

Functions

The variables PascTria and np are sometimes


called dummy arguments.
Function calls will generally take the form:

>> [OutVar1, OutVar2, OutVar3 ] = function_name(InVar1, InVar2, InVar3 ) <RET>

This function should be saved in a file called


<function_name.m> and the first line will read something
like:
function [OutArg1, OutArg2, OutArg3 ] = function_name(InArg1, InArg2, InArg3 )

MATLAB maps between the variables in the statement


that called the function and the (dummy) arguments in the
function definition based on their order.

Multiple input and output arguments

Now we look at an example


function with multiple input
arguments.
Calculate cross-sectional area
of a T-beam:

function Area = T_beam0( W1, H1, W2, H2 );


% --- T_beam0 --%
% Area = T_beam0( W1, H2, W2, H2 );
%
% This function computes the cross-sectional area of a T-section beam.
% ----------------------------------------------------------------Area = W1*H1+W2*H2;
% The cross-sectional area

Multiple input and output arguments

Perhaps we also want to obtain Ixx, Iyy and yc the


second moments of area and height of the centroid
above the bottom.
1
H
H

W1 H 1 1 W2 H 2 H1 2
A
2
2

3
3
W13 H1 W2 3 H 2
H1
H2

W1 H1 W2 H 2

I xx W1 H 1 yC
yC

I yy
W2 H 2 H 1

2
2

12 12
12 12

A W1 H1 W2 H 2
2

yC
2

function [Area, Ixx, Iyy, yC] = T_beam1( W1, H1, W2, H2 );


% --- T_beam1 --%
% [Area, Ixx, Iyy, yC] = T_beam1( W1, H2, W2, H2 );
%
% This function computes four geometric properties of a T-section beam.
% ----------------------------------------------------------------------Area = W1*H1+W2*H2;
% Cross-sectional area
yC = ((W1*H1)*(H1/2)+(W2*H2)*(H1+H2/2))/Area;
% Y coord of the centroid
Ixx = (W1*H1)*(yC-H1/2)^2 ...
% Start calc for Ixx ...
+ (W2*H2)*((H1+H2/2)-yC)^2 ...
% Continue calc for Ixx ...
+ (W1*H1^3)/12 + (W2*H2^3)/12;
% Final part of Ixx.
Iyy = (W1^3*H1)/12 + (W2^3*H2)/12;
% Calculation for Iyy.

MATLABs built-in functions

Note that most of MATLABs built-in commands are


functions.
e.g. sign(.)

A = 20*rand(10,1) 10 % Create vector of 10 numbers between -10 and 10.


A_signs = sign(A) % Run the built-in sign function returns -1 for
% negatives, 0 for zeros, and 1 for positives

sign(.) only allows one input argument and only returns


one output argument (check the help file if unsure of this!),
but other built-in functions allow multiple input arguments
and return multiple output arguments.
A = 20*rand(10,1) 10
A_max = max(A)
%
[A_max,ind] = max(A) %
%
%

% Create vector of 10 numbers between -10 and 10.


Run the built-in max function
Run the built-in max function again with 2 output
arguments the maximum value in A and the index
of the maximum entry

Help on functions

We can read help information on, say, T_beam3.m,


by typing

>> help T_beam3

<RET>

MATLAB places all of the commentary text on the screen


which appears after the first line of the function.
It is established practice in MATLAB programming of
functions to include, within this <help> text, a clear
indication of how the function may be called.
Built-in functions also follow this practice, e.g
>> help max

<RET>

The path command

For relatively small projects, it is generally


appropriate to keep all relevant files (i.e. scripts,
functions and data files) in the same folder.
For larger projects, the required files may be spread
over numerous folders.
In this case, all of the folders containing files that may
be required must be included in the MATLAB path.
The path function allows us to see which folders are
on the path, and add a folder to the path.
Type >> help path <RET> to find out more about
this.

Global variables

%
%
%
%

So far, variables have been passed into


functions as input arguments.
It is possible to declare variables as being
global; global variables can be accessed
globally, i.e. by any function (as long as that
function contains an explicit statement that
grants it access to that variable).
The following 2 programs work together:

--- main0 --This script shows that information can be passed into and out of
functions through <global> variables.
-----------------------------------------------------------------------

global x;
% Declare the variable x to be global.
x = 11.5;
% Assign a value to the global variable.
y = 1.5*pi-11.5;
z = func_xy( y );
% The value of <y> is passed into the function
disp([' The value of z is : ' num2str(z) ]);
disp([' The value of x is : ' num2str(x) ]);

function z_out = func_xy( y_in );


% --- func_xy --%
% z_out = func_xy( y_in );
%
% This function demonstrates that functions can access and change
% the information held in <global> variables.
% ----------------------------------------------------------------------global x;
% Declare the variable x to be global.
z_out = sin( x+y_in );
% Calculate the output variable
x = x+1;
% Deliberately modify x to demonstrate that
% this does change the value of x in the workspace.

10

Global variables
x started off as 11.5, then was both accessed and
modified in the workspace from the function
func_xy, becoming 12.5 even though x was not
an input or output variable.
Note that global variables do have the same name
within the functions that access them and in the
workspace.

Global variables

Global variables should be used only occasionally!


Main motivation is to simplify the communication of
variables when functions are called from within
functions, etc.

11

Global variables
Tips in using global variables:
1. who global gives a list of all the known global
variables
2. clear global deletes all global variables
3. Assigning a value to a variable and subsequently
declaring it to be a global variable leads to very
unpredictable results always declare it to be global
first and then assign a value.
People sometimes think it is useful to use global variables
rather than long lists of input and output variables. In these
cases, structures are a better option. Structures are
essentially variables that contain other variables, and are
beyond the scope of this course.

Functions that act on arrays

Sometimes we need to write functions which performs


vector-processing.
For example, we may wish to write a function to
calculates y cos ax bx 2
where a and b are fixed parameters and x may be a
scalar or vector.

function y = triv_func( a, b, x );
% --- triv_func --% y = triv_func( a, b, x );
% Illustration of writing a function to ensure it can act on arrays.
% ----------------------------------------------------------------------y = cos( a*x + b*(x.^2) );

% Calculate the output variable

Notice the use of the dot in x.^2 (in case x is a vector), but no dot in
a*x or b*(x because we expect both a and b to be scalars.

12

Example

10
0 <

For a function =
, plot
0
< 1
f(x) against x in the range 0,1 , for different
values of [0.2, 0.4, 0.6].

function y=fx(ix, ixa)


% y=f(x)
% Define function fx in the file fx.m
% Evaluation of a piecewise function
if(ix<ixa)
y=10*sin(pi*ix/ixa);
else
y=0;
end

Example
%
%
%
%

--- Main program --Calls functions fx to calculate y againest x in the range [0,1]
for different Xa values and plot the results.
----------------------------------------------------------------

clear all; close all; clc;


xa=[0.2, 0.4, 0.6];
x=(0:0.01:1);
iN=size(x,2);
y=zeros(iN, 3);
for ic=1:3
for id=1:iN
y(id,ic)=fx(x(id), xa(ic));
end
end
figure;
plot(x, y);
xlabel('x'); ylabel('f(x)');

13

Closing Remarks

Function provides a useful mechanism for code


reuse in Matlab.
Matlab has provided a rich set of internal functions.
Global variables can facilitate value passing in
function call, but should be used with caution.

14

Potrebbero piacerti anche