Documente Academic
Documente Profesional
Documente Cultură
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.
>>fred_radius=45;
>>fred_area=silly_c_area(fred_radius);
>>fred_radius
fred_radius=45;
>>pi
ans= 3.1416
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.
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
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
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,:)
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
24
25
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
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
dy
= f ( y, t ),
dt
y (0) = y0
30
dx
= kx,
dt
x(0) = 1
dx
= kdt , ln x = kt + C
x
x = exp ( kt )
31
Example ODE II
32
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
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
===========================================
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;
35
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:
36
============================================
prey.m script file to solve a system of ODEs
HDW 15/04/02
============================================
37
[ k_11*x(1) - k_12*x(1)*x(2)
-k_22*x(2) + k_21*x(1)*x(2)];
38
prey
100
0
0
5
time
10
5
time
10
20
predator
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
prey
200
100
0
5
time
10
5
time
10
50
0
100
50
100
predator
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
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
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
============================================
second.m script file to solve a 2nd-order
system of ODEs
HDW
15/04/02
============================================
43
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