Sunteți pe pagina 1din 44

Functions

Matlab is a powerful programming Language


You can write programmes (Functions) in Matlab and reuse them.
You can put groups of Functions together and create a library.
You can use your own Functions exactly as if they were built-in Matlab
functions
Functions are written in the Matlab Editor.
DO NOT CONFUSE FUNCTIONS WITH SCRIPT FILES !!

What is a Function (Programme) ?


A function is a collection of commands or statements that are executed in order
(This is like a script file,.however)
A function encapsulates these statements in a form that is modular or hidden from
the top level of Matlab. (This is not like a script file)
Matlab communicates to a function through its input arguments and output
arguments. There is no other way of getting information into and out of a function.
Modular (object oriented) ideas are at the heart of good programming practice.
function output_arguments=function_name(input_arguments)
Do some operations on the input arguments,
write the result to the output arguments
and then return

A Simple Example of a Function


Open the Matlab editor and type:
function area=c_area(radius)
area=pi*radius.^2;
Note: the word function is a key word in Matlab
Save this file as c_area.m (the name of this file and the name of the function must be the same !)
Now, in Matlab:
>>fred_radius=45;
>>fred_area=c_area(fred_radius)
fred_area = 6.3617e+003

Example Continued
Things to note:
In Matlab, variable names can be anything you like (they do not need to be called
area and radius as they are in the function).
Any combination of variables will work:
>>diam=10;
>>size=c_area(diam/2)
size= 78.5398
>>radius_list=[1, 4, 5.67];
>>area_list=c_area(radius_list)
area_list= 3.1416 50.2655 100.9987
Your new function works exactly the same way that a built in Matlab functions works.
Indeed, many built-in functions are just functions like our example which you can go
and look at.

Hidden Variables and Pass by Value: The Key Ideas I


In Matlab, what are the values of the variables area and radius when you have run
your programme ?
radius
??? Undefined function or variable 'radius'.
Matlab does not think the variable radius has been defined. The use of the variable
radius in the function is hidden from the top level of Matlab.
Suppose we define radius, run the function and then look at the value of radius again
>>radius=233;
>>fred_radius=45;
>>fred_area=c_area(fred_radius);
>>radius
radius=233;
The value of radius is not changed by the function. What the function does is
completely hidden from Matlab. What Matlab does is hidden from the function.

Hidden Variables and Pass by Value: The Key Ideas II


The only way of talking to a function is through its input and output arguments.
What happens is this:
The value of the input argument fred_radius is copied to the new local
variable radius. This value is used in the function.
The result of the calculation is stored in the local variable area.
When the function completes, the value of area is copied to the output argument
fred_area.
Then whatever was inside the function (the local variables area and radius) are
destroyed and lost.
Thus, the value of things are copied into and out of the function, but the function itself is
sealed from the outside world. Whatever is done inside the function has no effect
outside.
This idea of encapsulation is the most important idea in programming.

Hidden Variables and Pass by Value: The Key Ideas III


Now, we can proceed to write programmes that have no side effects:
function area=silly_c_area(radius)
% first manipulate some variables that
% are ues in Matlab
fred_radius=10;
pi=3;
% then do the calculation
area=pi*radius.^2;
% but nothing will change in Matlab

>>fred_radius=45;
>>fred_area=silly_c_area(fred_radius);
>>fred_radius
fred_radius=45;
>>pi
ans= 3.1416

Functions With More Than One Input Variable


Multiple arguments: Back in the editor,
function f=sawtooth(t,T)
% SAWTOOTH waveform generator
% f=SAWTOOTH(t,T) computes values for a sawtooth
% having period T at the values in t
% HDW 12/04/02
f=10*rem(t,T)/T;

Then in Matlab
>>t=0:0.1:10;
>>f=sawtooth(t,2);
>>plot(t,f)
Functions of any number of input arguments can be written. Arguments can be either
scalars, vectors or matrices (providing your function can handle this).

HELP !!
The comments placed immediately after the function definition are the help:
>>help sawtooth
Matlab prints out the first lot of comments in a function as the help for the function.
In fact, Matlab is mainly built on functions that are written this way using only primitive
commands. Take a look at the Matlab source directories for some good examples.

Functions with Multiple Output Variables


Matlab functions can also return more than one variable
function [area,circum]=circ_calc(radius)
% function to compute the area and circumfrence of a circle
% [area,circum]=circ_calc(radius)
area=pi*radius.^2;
circum=2*pi*radius;

In Matlab:
>> [area_list,circum_list]=circ_calc(radius_list);
If you omit output variables, then the first one is assigned (but all calculations are
still performed ):
>> area_list=circ_calc(radius_list);
Any number of output variables can be employed
[Variable numbers are possible, but beyond the scope of this course]

10

Functions of Functions
You can call your Matlab functions from another Matlab function. For example:
function [deriv,maxs,mins,inflecs]=my_analysis(afunction,xmin,xmax,tick)
% a programme to compute and label the extrema of a function
% [deriv,maxs,mins,inflecs]=my_analysis(afunction,xmin,xmax,tick)
% HDW 12/04/02
% set up the space and evaluate the function
x=xmin:tick:xmax;
y= eval(afunction);
% first derivative
dydx=my_derivs(y,x);
% locate extrema
extrema=my_zeros1(dydx,y);
% second derivative is just derivative of first derivative
ddydx=my_derivs(dydx,x);

11

Functions of Functions
Functions can be nested as deep as required.
Functions can also call themselves (recursive):
function result=my_fact(n)
%
% A function to recursively compute a factorial
% result=my_fact(n)
% HDW 12/04/02
if n<= 1
result=n; % base case
else
result=n*my_fact(n-1); % otherwise n * factorial of n-1
end

12

How to Write Good Programmes: Some Guidelines I


1. Decide on an appropriate structure
a. Break down the problem into solvable modules
b. Define Inputs and outputs to modules and what each module should do
c. Modules should be made small and simple
2. Write the code bottom-up
a. Write and test the core modules first
b. Part by-part assemble larger programmes, maybe using several levels of
function nesting.
c. At each stage, test that the code does what you think
3. In each module have the following parts:
a. Detailed Help . It will not be obvious next week !
b. Test the input variables:
if x < 0
error(X must be positive)
end
c. write the main block of code with plenty of space and comments
d. Use Meaningful Variable Names

13

Polynomials, Interpolation
and Data Analysis

14

Polynomials
Matlab has a number of powerful functions for dealing with polynomials
Polynomials are of great value in data analysis for curve fitting and approximation
In Matlab, a polynomial is represented by a row vector of its coefficients.
For example the polynomial
x4 - 12x3 - 25x +116
is entered as
>> p=[ 1 -12 0 25 116]
Note:
Starts at the highest order term
Includes padded zeros as necessary

15

Polynomial Algebra I
The function roots finds the roots of a polynomial:
>>r=roots(p)
r=
11.7473
2.7028
-1.2251 + 1.4672i
-1.2251 - 1.4672i
The function poly does the opposite of roots.
>>pp=poly(r)
Sometimes need to get rid of left over complex parts:
>> pp=real(pp)
Matlab adopts the convention that polynomials are row vectors and roots are
column vectors.

16

Polynomial Algebra II
Multiplication: Matlab uses the function conv to multiply two polynomials:
eg: a(x)=x3 + 2x2 + 3x +4, b(x) = x3 + 4x2 + 9x +16
>>a=[1 2 3 4]; b=[1 4 9 16]
>>c=conv(a,b)
c= 1 6 20 50 75 84 64
>>
The result is
c(x) = x6 + 6x5 + 20x4 + 60 x3 + 75x2 + 84x + 64
Addition: If the polynomials are of the same order, then normal vector addition can be
used to add two polynomials:
>> d=a+b;
Otherwise the vector must be padded:
>>e=c+[0 0 0 d]

17

Polynomial Algebra III


Division: Matlab uses the function deconv to do polynomial division:
>> [q,r]=deconv(c,b)
q=
1 2 3 4
r=
0 0 0 0 0 0
This says that the result of dividing c by b gives the quotient polynomial q and the
remainder r, which is zero in this case since the product of b and q is exactly c.

18

Polynomial Evaluation
Matlab has a special function polyval to evaluate polynomials:
>>x=linspace(-1,3); % choose 100 data points (default) on -1 3
>>p=[1 4 -7 -10];
% polynomial is x^3 + 4x^2-7x-10
>>v=polyval(p,x);
>>plot(x,v); title(x^3+4x^2-7x-10);
Note also the function residue for partial fractions
>>num=10*[ 1 2]; den=poly([-1; -3; -4]);
>>[res,poles,k]=residue(num,den)
This allows partial fraction expansions of a polynomial quotient

19

Curve Fitting I
Matlab provides a number of facilities to allow curve fitting. These are useful in
data analysis and data compression.
Example data:
>>x=[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1]
>>y=[-0.447 1.978 3.28 6.16 7.08 7.34 7.66 9.56 9.48
9.30 11.2]
polyfit fits a fixed order polynomial to the data
>>n=2;
>>p=polyfit(x,y,n)
p= -9.8108 20.1293 -0.0317
This corresponds to the polynomial
-9.8108x2 + 20.1293x - 0.0317

20

Curve Fitting II
To see what this looks like:
>>xi=linspace(0,1,100);
>>z=polyval(p,xi);
>>plot(x,y,o,x,y,xi,z,:)
What order is best ? Eleven data points so a 10th order polynomial ?
>>pp=polyfit(x,y,10);
>>zz=polyval(p,xi);
>>plot(x,y,o,xi,z,:xi,zz,:)

High Order Polynomials tend to be unstable

21

One-Dimensional Interpolation
By default, Matlab uses linear interpolation between data points:
>>x1=linspace(0,2*pi,60);
>>x2=linspace(0,2*pi,6);
>>plot(x1,sin(x1),x2,sin(x2),-);
If you want to do better than this, then MATLAB provides a built-in function:
interp1
>>hours=1:12; % must be monotonic
>>temps=[5,8,9,15,25,29,31,30,22,25,27,24];
>>plot(hours,temps,hours,temps+);
To linearly interpolate use:
>>t=interp1(hours,temps,9.3) % temp at 9.3 hours
t=22.9000
>> t=interp1(hours,temps,[3.2 6.5 7.1 11.7])
t=10.2 30.0 30.9 24.9

22

One-Dimensional Interpolation
interp1 can also use cubic splines (splines) for smoother results:
>> t=interp1(hours,temps,[3.2 6.5 7.1 11.7],spline)
t=10.2 30.0 30.9 24.9
Plot:
>>h=1:0.1:12;
>>t=interp1(hours,temps,h,spline);
>>plot(hours,temps,-,hours,temps,+,h,t)

23

Two Dimensional Interpolation


Two dimensional interpolation is also possible for
elevation functions z=f(x,y)
Plate temperature distributions:
>>width=1:5; % plate width index
>>depth=1:3; % plate depth index
>>temps=[82 81 80 82 84;
79 63 61 65 81;
84 84 82 85 86];
Interpolation in one direction:
>>wi=1:0.2:5; % points across width
>>d=2; % at a depth of 2
>>zlinear=interp2(width,depth,temps,wi,d); % linear
>>zcubic=interp2(width,depth,temps,wi,d,cubic);
>>plot(wi,zlinear,-,wi,zcubic); grid;
>>title([Temperature at Depth = num2str(d)])

24

Two Dimensional Interpolation


Interpolation in two dimensions:
>>mesh(width,depth,temps)
>>di=1:0.2:3;
>>wi=1:0.2:5;
>>zcubic=interp2(width,depth,temps,wi,di,cubic);
>>mesh(wi,di,zcubic)
>>xlabel(Width of Plate); ylabel(Depth of Plate);
>>zlabel(Degrees Celsius); axis(ij); grid;

25

A Note on 3-D data representation


Often interested in presenting 3-D data. For
example

z=

1
1 + x2 + y 2

To set up a range
y=-1:0.1:2; x=-2:0.1:2;
[x_grid, y_grid]=meshgrid(x,y); % generate an appropriate z
z = 1./(1 + x_grid.^2 + y_grid.^2);
mesh(x,y,z)
xlabel('X'); ylabel('Y'); zlabel('Z')

26

A Note on 3-D data representation II


Alternatively:
surf(x,y,z)
xlabel('X'); ylabel('Y'); zlabel('Z')
title('Surface plot')

Also:
meshc(x,y,z), surfc(x,y,z), surfl(x,y,z), contour(x,y,z,16)

1
0.8
0.6
0.4
0.2
0
2
2

1
0

0
-1
-1

-2

27

A Picture of Sydney

28

A Final Word

[x,y,z]=peaks(30);
mesh(x,y,z)
title('Peaks')

Gradients of Peaks
3

[DX,DY]=gradient(z,.5,.5);
contour(x,y,z,10)
hold on
quiver(x,y,DX,DY)
title('Gradients of Peaks')
hold off

-1

-2

-3
-3

-2

-1

29

Solving Differential Equations

Matlab provides a number of tools for solving ordinary differential equations


(ODEs), in particular, Matlab solves equations in the form

dy
= f ( y, t ),
dt

y (0) = y0

Using the built-in function:


>>Y=Ode23(f,tspan,y0)
Ode23 is the simplest solver. There are other solvers for specific types of
problems, but these are beyond the scope of this course. Do help ode23 for
more detailed information.

30

Example of simple ODE I

Consider the problem of integrating a first-order ODE

dx
= kx,
dt

x(0) = 1

the solution is,

dx
= kdt , ln x = kt + C
x
x = exp ( kt )

31

Example ODE II

Type in the script file odesolver.m


% ===========================================
% odesolver.m script file to solve an
% ordinary differential equation (ODE)
% HDW 15/04/02
% ===========================================
global k_value % need to use this value in the function
disp('Program to integrate x_dot = k * x')
k_value = input('Enter the value of k: ');
time_span = 0:0.1:10; % specify the time span
x_0 = 1.0;
% initial condition
% integrate the ODE
[t, x] = ode23('ode1', time_span, x_0);
plot(t,x); xlabel('time'); ylabel('x')

32

Example ODE III


The function named ode1.m to be integrated
function xdot = ode1 (t, x);
% ode1.m: example of an ode
% syntax
xdot = ode1(t, x)
% HDW
15/04/02
% ==========================
global k_value
xdot = k_value*x;
1

Then run the script file

0.9
0.8
0.7
0.6
x

odesolver
Program to integrate x_dot = k * x
Enter the value of k: 0.2

0.5
0.4
0.3

See the plot

0.2
0.1

5
time

10

33

Example ODE IV
Can also pass arguments through an argument list (better):
%
%
%
%
%

===========================================
odesolver2.m script file to solve an ODE
HDW 15/04/02
===========================================

disp('Program to integrate x_dot = k * x')


k_value = input('Enter the value of k: ');
time_span = 0:0.1:10; % specify the time span
x_0 = 1.0;
% initial condition
% integrate the ODE
[t, x] = ode23('ode2', time_span, x_0, [], k_value);
plot(t,x); xlabel('time'); ylabel('x')

34

Example ODE V:
Then the function
function xdot = ode2 (t, x, flag, k);
% ode1.m: example of an ode
% syntax
xdot = ode2(t, x)
% HDW 15/04/02
% ==========================
xdot = k*x;

It is generally a better policy to not use global variables

35

Integrating a System of ODEs I


Example, Predator Prey.
Population of Prey is N1
Population of Predator is N2

dN1
= k11 N1 k12 N1 N 2 , N1 ( 0 ) = N10
dt
dN 2
= k21 N1 N 2 k22 N 2 , N 2 ( 0 ) = N 20
dt
Note, At equilibrium:

0 = k11 N1 k12 N1 N 2 N 2,equil = k11 k12


0 = k21 N1 N 2 k22 N 2 N1,equil = k22 k21

36

Integrating a System of ODEs II


%
%
%
%
%

============================================
prey.m script file to solve a system of ODEs
HDW 15/04/02
============================================

disp('Program to solve the predator-prey problem')


k_11 = input('Enter the value of k_11: ');
k_12 = input('Enter the value of k_12: ');
k_21 = input('Enter the value of k_21: ');
k_22 = input('Enter the value of k_22: ');
N_0(1) = input('Enter initial population of prey: ');
N_0(2) = input('Enter initial population of predator: ');
time_span = 0:0.1:10; % specify the time span
% integrate the ODE
[t, N] = ode23('ode3', time_span, N_0, [], k_11, k_12, k_21, k_22);
N_1 = N(:,1);
N_2 = N(:,2);
subplot(3,1,1); plot(t,N_1); xlabel('time'); ylabel('prey')
subplot(3,1,2); plot(t,N_2); xlabel('time'); ylabel('predatory')

37

Integrating a System of ODEs II


(Vector) Function to be integrated
function xdot = ode3(t, x, flag, k_11, k_12, k_21, k_22);
% ode3.m: example of a system of odes
% syntax
xdot = ode3(t, x)
% NP-T
14/04/99
% ====================================
xdot =

[ k_11*x(1) - k_12*x(1)*x(2)
-k_22*x(2) + k_21*x(1)*x(2)];

Note, argument to function must be a column vector

38

Integrating a System of ODEs III


Example Run:

N1,equil = k22 k21 = 100


Note Cyclic population levels

prey

100

0
0

5
time

10

5
time

10

20
predator

N 2,equil = k11 k12 = 10

200

10

0
20
predator

prey
Program to solve the prey-predator problem
Enter the value of k_11: 1
Enter the value of k_12: 0.1
Enter the value of k_21: 0.01
Enter the value of k_22: 1
Enter the initial population of prey: 200
Enter the initial population of predator: 10

10

0
40

60

80

100

120
prey

140

160

180

200

39

Integrating a System of ODEs IV

N1,equil = k22 k21 = 100

prey

200
100
0

5
time

10

5
time

10

50

0
100

50

Note: Different initial conditions have


very different results

100
predator

N 2,equil = k11 k12 = 10

300

predator

prey
Program to solve the prey-predator problem
Enter the value of k_11: 1
Enter the value of k_12: 0.1
Enter the value of k_21: 0.01
Enter the value of k_22: 1
Enter the initial population of prey: 200
Enter the initial population of predator: 75

50

100

150

200

250

prey

40

Integrating a high-order ODE I


First, convert the ODE into a set of first-order ODEs, then use ODE23 to solve them
Example: 2nd order oscillator:
d 2x
dx
2
2
+
2

x
=

f (t )
n
n
n
2
dt
dt
x ( 0 ) = x0 , xC ( 0 ) = xC0

where n is the natural frequency, is the damping factor, and is the driving
frequency

41

Integrating a high-order ODE II


Define:

x1 = x, x2 =

dx
dt

dx1
= x2
dt
dx2
= 2 n x2 n2 x1 + n2 f ( t )
dt
x1 ( 0 ) = x0 , x2 ( 0 ) = x0
With f(t)=1 (a step input).

42

Integrating a high-order ODE III


%
%
%
%
%

============================================
second.m script file to solve a 2nd-order
system of ODEs
HDW
15/04/02
============================================

disp('Program to solve a 2nd-order ODE')


omega_m = input('Enter omega_n: ');
zeta = input('Enter zeta: ');
x_0(1) = input('Enter x(0): ');
x_0(2) = input('Enter xdot(0): ');
time_span = 0:0.1:20; % specify the time span
% integrate the ODE
[t, x] = ode23('ode4', time_span, x_0, [], omega_m, zeta);
displacement = x(:,1); velocity
= x(:,2);
subplot(3,1,1); plot(t,displacement);
xlabel('time'); ylabel('displacement');
subplot(3,1,2); plot(t,velocity);
xlabel('time'); ylabel('velocity');
subplot(3,1,3); plot(displacement, velocity);
xlabel('displacement'); ylabel('velocity')

43

Integrating a high-order ODE IV


Function to integrate:
function xdot = ode4 (t, x, flag, o_m, zeta);
% ode3.m: example of a system of odes
% syntax
xdot = ode4(t, x)
% NP-T
14/04/99
% ==========================
displacement

xdot =

[ x(2)
-2*zeta*o_m*x(2) - o_m^2*x(1) +

o_m^2];

10
time

12

14

16

18

20

10
time

12

14

16

18

20

second
Program to solve a 2nd-order ODE
Enter omega_n: 1
Enter zeta: 0.2
Enter x(0): 0
Enter xdot(0): 0

0.5
0
-0.5
1

velocity

Run:

velocity

0.5
0
-0.5

0.2

0.4

0.6

0.8
displacement

1.2

1.4

44

1.6

S-ar putea să vă placă și