9. 21 Common tasks in MATLAB 42
22 Worked Examples in Programming 52
23 Concluding Remarks 62
List of Figures
1 Plot of humps(x). . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2 Motion of Simple Pendulum. . . . . . . . . . . . . . . . . . . . . 16
3 quiver displays angle and magnitude of data. . . . . . . . . . . . . 17
4 Changing properties of a graphic object. . . . . . . . . . . . . . . 19
5 Creating simple inset plots. . . . . . . . . . . . . . . . . . . . . . 20
6 The user can select the lower left and top right corners of a box,
and display that portion in another part of the window. . . . . . 21
7 patch(X,Y,'c') creates a
10. lled polygon whose vertices are given
in X and Y using the colour 'c'. EdgeColor is used to highlight
the patch. Note the
11. ll area for negative values of y. . . . . . . . 22
8 Greek letters, subscripts, etc. in graph annotation. The default
interpreter is TeX. . . . . . . . . . . . . . . . . . . . . . . . . . . 23
9 A simple pushbutton. When pressed displays 'Hello' in the com-mand
window, and recon
12. gures itself as a quit button. . . . . . . 25
10 Colour sampler. Adjust the values the Red, Green and Blue
component using the sliders. A sample of the colour is shown as
a patch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
11 Playing with buttons. Demonstrates the use of embedding the
CallBacks within the same function. . . . . . . . . . . . . . . . . 30
12 Triangular hat function . . . . . . . . . . . . . . . . . . . . . . . . 33
13 An image taken under UV. . . . . . . . . . . . . . . . . . . . . . 60
14 An image taken under UV after converting to black and white. . 60
2
13. Abstract
MATLAB is an interactive package to perform matrix based computations. The
package also contains several built-in functions to perform routine computations
in Numerical Analysis, Signal Processing, Control Systems and wide variety of
special functions in Applied Mathematics. Many specialist toolboxes are being
continually added to the above collection.
Finally, the package provides excellent facilities to obtain two/three dimen-sional
plots of your data. A short section on HandleGraphics is included to
provide the elementary principles of customizing the plots.
A new section on developing GUIs is included. One must exercise enormous
caution in developing GUIs in matlab as the code can get enormously large very
quickly.
In this guide, only a subset of MATLAB functions dealing with Matrix Algebra
and Numerical Analysis are described in some detail. Further details on these
and other functions in the above mentioned areas can be found in [MATLAB
High-Performance Numeric Computation and Visualization Software, User's
Guide, The Math Works Inc., 1993 and Signal Processing Tool Box, by J.N.
Little and L.Shure, The Math Works Inc., 1988].
14. Revision History
This User Guide has started its life around 1992. First version is made available
for general use through the Compute Center in 1993. Since then the User Guide
has under gone several changes taking into account some of the mistakes, errors
and typos suggested by students, colleagues and well wishers. Thank you all for
your input. With this version I have decided to include this section as a way of
keeping track of additions and deletions.
Some new concepts from Matlab Version 5.2 are now included.
20 October 1995 Additional examples on Graphics and a section on Handle Graph-ics.
16 November 1995 Added model solutions to Tutorial Sheet.
10 September 1997 Added two Sections { GUIs and Common Tasks in Matlab. Re-placed
MATLAB Quick Reference with an alphabetical list of mat-lab
commands.
18 September 1997 Minor corrections and addition to suggested solution for 4(e)
18 November 1998 Added switch, and subfunctions.
Modi
15. ed eye(A), etc. They no longer work in V5.2
17 September 1999 Correction to the output of A 0 in the Table. Shows three rows
now to be consistent with the de
16. nition of A above.
3 November 2006 Changed the address block.
1 November 2012 Changes to functions calling functions.
9 October 2014 re-captured all
17. gures; quad replaced by integral; changes to pa-rameter
passing to functions; included an index for easy reference
1
18. 1 Getting Started
MATLAB is an interactive software package for scienti
19. c and engineering compu-tation.
MATLAB is an abbreviation for MATrix LABoratory and was originally
written (in the early 70s) to provide easy access to matrix software developed
by the LINPACK and EISPACK projects. Since then it has embraced virtually
every branch of numerical mathematics.
Matlab can be started on Unix/Linux by typing the command matlab at
unix prompt or from the Start button on Windows platform.
The programs and code snippets are developed using MATLAB Version
8.3.0.532 (R2014a). The MATLAB commands can be issued at the double angled
prompt .
Now you can issue any MATLAB command. If you are a
20. rst time user, you
are urged to go through the demonstration programs which illustrate its various
capabilities. To invoke this program, issue the command
demo
at MATLAB prompt, ; and select an appropriate section.
There is also a hyper-documentation facility which is invoked by typing doc
at the MATLAB prompt.
1.1 Help!
Type help at Matlab prompt for command line help. The same material can
also be accessed via the web browser using doc.
2
22. ned as a list enclosed by square brackets, where the rows are
separated by ; and the elements are separated by a blank or a comma. For
example,
A = [1 2 3; 4 5 6 ; 7 8 9]
Matrix elements can be de
23. ned using any valid MATLAB expression. Here, pi and
i are prede
25. nes a row vector x = [i
p
2 cos(=4)]. Individual entries of a matrix are
referenced with indices enclosed by parentheses, ( and ). Thus, x(2) corresponds
to the second element of the vector in the above example. By de
26. ning x(5) =
sqrt(3), automatically increase the dimension and results in the vector
x = [i 1.4142 0.7071 0.0000 1.7320]
In a similar fashion bigger matrices can be de
27. ned from smaller matrices.
For example,
r = [10 11 12];
A = [A;r];
would result in
1 2 3
4 5 6
7 8 9
10 11 12
Smaller matrices can be extracted from bigger matrices, using
A = A(1:3,:)
would result in the original matrix A.
3 Matrix Operations
Expressions involving matrix operations (or for that matter any numerical com-putation)
are entered almost exactly as you would write on paper using standard
mathematical notation. For example, to add the matrices A and B and then
multiply by matrix C one would enter
(A+B)*C
at the prompt level. Standard matrix operations and the corresponding MATLAB
syntax are shown in the following table.
3
28. Matrix operation MATLAB syntax
addition and multiplication (A + B) C
transpose of A A′
inverse of A inv(A)
Matrix division
To solve A X = B A B
To solve X A = B B=A
power of A A^r
4 Point-wise Operations
Element-by-element arithmetic of arrays is performed using : and := for multi-plication
and division respectively. For example, if
x = [1 2 3]
y = [4 5 6]
then the following table illustrates various point-wise operations on x and y as
de
29. ned above.
Z = evaluates to remarks
x: y [4 10 18] [1 4 2 5 3 6]
x:y [4 2:5 2] [ 4
1 ; 5
2 ; 6
3 ]
x:=y [0:25 0:4 0:5] [ 1
4 ; 2
5 ; 3
6 ]
x:^y [1 32 729] [14; 25; 36]
x:^2 [1 4 9] [12; 22; 32]
2 :^x [2 4 8] [21; 22; 23]
What does 2 :^[x y] evaluate to?
5 Relational Operations
Two matrices of equal dimension can be compared, using the relational opera-
tors, ;=; ;=;== (equal to), and ~ = (not equal to). The result of such
an operation is a 0-1 matrix of same dimension.
30. nd is a helpful command which
returns the index; and can be used in conjunction with relational operators. For
example,
x = [1 2 3 4 5 6 7 8 9 5];
i =
32. would return
[4 5 6 7 8 9 10]
for i. Now using
x(i) = 10*ones(i);
modi
33. es the elements x(4),x(5),x(6) etc. Here the command ones(i) generates
a matrix of dimension i whose elements are all 1. As a result the the vector x
contains
[1 2 3 10 10 10 10 10 10 10]
If a = [0.75 35 -22.0 8.0 35.0 6.2], what is returned by the
command i =
35. ning Vectors
A sequence of numbers are generated by the command
x = 1:5
which returns the vector
[1 2 3 4 5]
The precise meaning of the symbol ':' depends on the context.In this case it is
to be understood as a means of separating the lower limit and upper limit of
the sequence. A default step size of 1 is understood. A required step size can
be de
36. ned as follows
x = 1:0.5:2
which results in the vector
[1 1.5 2]
Negative increments are also permissible, and the command
x = 6:-1:1
yields
[6 5 4 3 2 1]
To generate n points in the closed interval [a; b] (no step length is speci
37. ed),
one can use
x = linspace(a,b,n)
Thus
x = linspace(-1,1,5)
generates the vector containing
[1 0:5 0 0:5 1]
5
38. 7 Addressing Matrix Elements
Individual matrix elements can be referenced using subscript notation. For the
matrix
A =
1 2 3 1
4 5 6 2
7 8 9 3
A(3; 2) refers to 8. The elements can also be altered. For example,
A(3; 2) = A(2; 3) + A(3; 3)
results in the matrix
A =
1 2 3 1
4 5 6 2
7 15 9 3
A subscript can also be a vector. Thus specifying A(1 : 2; 3) yields
39. rst two
rows of the third column, i.e, [3 6]. A colon, ':' can be used as a wild card to
refer to all the elements in a column or a row. Thus A(:; 2) refers to all the
elements in the 2nd column. The following table summarises the eects of some
useful commands.
command result
A(2; :) (
[4 5 6 2]
A(2 : 3; 2 : 4)
5 6 2
15 9 3
)
A(:; :) is the same as A
A(:) matrix A arranged as a single column
max(A) row containing maximum element of columns of
A, i.e., [7 15 9 1]
max(max(A)) 15
40. nd(A == max(max(A))) 6 ,returns linear index where the matrix is treated
as a single column.
A 0
0 0 0 1
0 0 0 1
0 0 0 1
8 Referencing with 0-1 vectors
The 0-1 vectors are usually created from relational operations, which can be
used to reference submatrices. For example,
x = [1 2 3 4 5 10 12 15 16]
Then the following commands
6
41. i = x =10
returns the 0-1 vector
i = [0 0 0 0 0 1 1 1 1]
and referring to those elements bigger than or equal to 10 as
x = x(i)
would return
x = [10 12 15 16]
What is the outcome of the command
x = x( (x = 4) (x 12) )?
9 Pre-de
43. ned for quick reference and
for your own use; and some of these matrices are listed below.
MATLAB syntax purpose
hadamard(k) returns the Hadamard matrix of order n = 2k
hankel(c) Hankel matrix
hankel(c,r) See Manual or use Help
hilb(n) Hilbert matrix of dimension n
invhilb(n) inverse of Hilbert matrix
magic(n) magic square of order n
There are some useful matrices which are mostly used in point-wise operations
and these are illustrated below which are self-explanatory.
7
44. matrix output
ones(3)
1 1 1
1 1 1
1 1 1
Z = zeros(3,4)
0 0 0 0
0 0 0 0
0 0 0 0
ones(Z)
1 1 1 1
1 1 1 1
1 1 1 1
eye(4)
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
eye(Z)
1 0 0 0
0 1 0 0
0 0 1 0
rand(3)
0:2190 0:6793 0:5194
0:0470 0:9347 0:8310
0:6789 0:3835 0:0346
rand(Z)
0:0535 0:0077 0:4175 0:9304
0:5297 0:3834 0:6868 0:8462
0:6711 0:0668 0:5890 0:5269
10 Control Flow
MATLAB provides two commands for repeated execution of a group of commands
and these are illustrated with examples.
10.1 for end
A group of statements are executed a
45. xed number of times with the help of for
end construct. For example,
for j=1:5,x(j) = 0,end
assigns 0 to the
50. ne the Vandermonde matrix
xn−1
1
x21
x1 1
xn−1
2
x22
x2 1
...
...
xn−1
n
x2
n xn 1
starting with the vector [1 0 1 3 5] one can use the following commands.
x = [-1 0 1 3 5];
n = max( size(x) );
a(:,n) = ones(n,1);
for j=n-1:-1:1
a(:,j) = x' .* a(:,j+1);
end
10.2 while end
To execute a group of statements repeatedly subjected to a constraint while
end construct is used. For example,
n = 1;
while prod(1:n) 1.e100,
n = n+1; end
will return the
51. rst integer n for which n! is a 100 digit number. eps in MATLAB
is de
52. ned as follows.
small = 1;
while (1+small ~= 1)
small = small/2;
end
small = small*2
Try the above lines on the computer you are using to
53. nd eps.
10.3 if else(if) end
Finally, MATLAB provides if else(if) end construct for conditional branching.
For example, to de
54. ne a 5 5 matrix A such that
aij = 2 ,i = j
= -1 ,ji jj = 1
one can issue the following commands.
for i=1:5,
for j=1:5,
if i==j,
9
55. a(i,j) = 2;
elseif abs(i-j) == 1,
a(i,j) = -1;
else
a(i,j) = 0;
end
end
end
break command is used to exit out of for or while loops as illustrated below.
eps = 1;
for i = 1:1000,
eps = eps/2;
if (1+eps = 1), break ,end
end
eps = eps*2
10.4 switch ... case ...otherwise ... end
switch block enables conditional execution. In its simplest form, switch executes
the
56. rst case where switch expr == case expr. The following example illustrates
the usage.
Example 10.1 Evaluate linear or quadratic or cubic function depending on the
user input.
% script to demonstrate switch
order = input('What is the order of the polynomial?');
x = -2:.1:2;
switch order
case 3, disp('Cubic')
y = x.^3;
case 2, disp('Quadratic')
y = x.^2;
case 1, disp('Linear')
y = x;
otherwise, disp('Unknown order')
end
plot(x,y), grid
11 Using an Editor
The built-in editor is invoked at the command prompt as
edit
and comes with host of utilities including debugging and dynamic tips for writing
ecient code. Pay attention to those orange scrolls on the right hand side.
10
60. le containing a sequence of MATLAB commands,
which can be invoked at MATLAB prompt level. These
61. les must have extension
'.m' and reside in MATLAB sub-directory of your area. The following is an example
of a script to generate the
62. rst few Fibonnaci numbers.
f = [1 1];
i = 1;
while f(i)+f(i+1) 1000
f(i+2) = f(i)+f(i+1);
i = i+1;
end
Let us say the above lines have been stored in a
63. le called, fib.m in a
directory, ~username/matlab. Then the above lines are invoked by simply
typing in the name of the
64. le, in this case fib at the MATLAB prompt.
In contrast a function
71. rst
function is called the primary function and the rest are referred to as subfunc-tions.
Their scope is limited to the scope of the primary function. The variables
de
72. ned in the primary function are not available inside any of the subfunctions
unless declared global.
Example 12.1 Compute arithmetic, geometric and harmonic mean of a list of
numbers.
function [am, gm, hm] = amgmhm( list )
% compute arithmetic, geometric and harmonic mean
n = length( list );
am = amean( list, n );
gm = gmean( list, n );
hm = hmean( list, n );
11
73. function a = amean( x, n )
%arithmetic mean
a = sum(x)/n;
function g = gmean( x, n )
%geometric mean
if all( x 0 )
g = prod( x )^(1/n);
else
error('All elements need to be positive for GM');
end
function h = hmean( x, n )
%harmonic mean
if all( x 0 )
h = (1/n)* sum( 1 ./x );
else
error('All elements need to be positive for HM');
end
Typical output from this function is
x = 1:5
x =
1 2 3 4 5
[a,b,c] = amgmhm( x )
a =
3
b =
2.6052
c =
0.4567
12
75. ned in the primary function need to be passed
explicitly as an argument to subfunctions.
13 Numerical Computations
Besides matrix computations, MATLAB provides several commands or scripts to
perform routine numerical computations such as numerical integration, dieren-tiation,
approximate solutions of nonlinear equations, optimization and numer-ical
solution of dierential equations. There are extensive facilities to display
both one dimensional and two dimensional plots and provides a very simple
mechanism to obtain hard copies of your precious plots. Some of these func-tions
are illustrated below. De
76. ne the function
y(x) =
1
(x 0:3)2 + 0:01
+
1
(x 0:9)2 + 0:04
6:0
in an M-
77. le called humps.m as
function y = humps(x)
y = 1 :=((x :3):^2 + :01) + 1 :=((x :9):^2 + :04) 6;
To display the graph of the function in the interval 1 x 2, issue the
commands
x = -1:.01:2;
plot(x,humps(x)), grid, title('Plot of humps(x)')
xlabel('x'), ylabel('y = humps(x)')
and the plot is shown in Fig. 1.
To integrate the above function between 0 to 1, use the command
area = integral(@humps,0,1)
area =
29.8583
The integration is performed using adaptive recursive Simpson's rule. For the
location of the local minima in the interval 0:5 x 1 is obtained by using
xmin = fminunc( @sin, pi)
xmin =
4.7124
F = @(x) 100-humps(x)
[x,fval] = fminunc(F,0.5)
x =
13
78. 100
80
60
40
20
0
−20
Plot of humps(x)
−1 −0.5 0 0.5 1 1.5 2
x
y = humps(x)
Figure 1: Plot of humps(x).
0.3004
fval =
3.4986
As can be observed from the plot of the function, humps(x) has two zeros
in the neighbourhoods of x = 0 and x = 1. These zeros are obtained using the
commands
zero1 = fzero( @humps, 0 )
zero1 =
-0.1316
zero2 = fzero( @humps, 1 )
zero2 =
1.2995
13.1 Dierential Equations
Numerical approximations for the solutions of dierential equations are com-puted
using either ode23 or ode45. Both of the routines use automatic step size
14
79. Runge-Kutta-Fehlberg integration methods. ode23 uses a simple 2nd and 3rd
order pair of formulae for medium accuracy, while ode45 uses 4th and 5th order
formulae for higher accuracy.1 For example, consider the second order nonlinear
dierential equation
y+ 0:3 y_ +
g
l
sin y = 0
with the initial conditions
y(0) =
y_(0) = 0
First one must express the above dierential equation as a system of two
80. rst
order equations which is achieved by setting y1 = y_2 and y2 = y. Thus, we
obtain
y_1 = 0:3y1 g
l
sin y2
y_2 = y1
and the initial conditions transform to
y1(0) = 0
y2(0) =
Next the pair of
82. le, say, shm.m which
is required to invoke ode23. For illustration purposes choose g = 9:8 ms−2 and
l = 1 m.
function ydot = shm(t,y)
ydot(1) = -0.3*y(1) - 9.8* sin ( y(2) );
ydot(2) = y(1);
ydot = ydot';
Further choose the initial angular displacement = 0:25 radians. Now to
simulate the motion of the pendulum for the
85. nal];
y0 = [0 0.25];
[t,y] = ode23( @shm,tspan,y0 );
plot(t,y), grid, legend('Displacement','Angular velocity')
xlabel('t'), ylabel('Displacement and Angular velocity')
and the graphical output is shown in Fig. 2.
1For further details see G.E.Forsythe, M.A.Malcom and C.B. Moler, Computer Methods
for Mathematical Computations, Prentice Hall, 1977.
15
86. Displacement
Angular velocity
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
0 2 4 6 8 10 12 14 16 18 20
t
Displacement and Angular velocity
Figure 2: Motion of Simple Pendulum.
14 Graphics
Apart from the straight forward x-y plots, MATLAB provides a wide range of
plot styles, which can be found in MATLAB Quick Reference. For an interesting
collection of plots see MATLAB demo program.
As an example, mesh, contour and quiver are illustrated below. The sub-
plot(mnp) divides the plot area into m by n cells and uses the p-th cell to
display the plot. We wish to generate the surface z = x exp(x2 y2) over the
domain x 2 [2; 2] and y 2 [2; 2]. Using the command sequence
% sandq.m - surface and quiver plot of
% z = x exp( -x^2 - y^2)
%
clf % clear figures
[x y] = meshgrid(-2:.2:2,-3:.2:3); % define the grid
z = x .* exp( -x.^2 - y.^2); % define the function
subplot(121), mesh(z), grid % split the
% plotting area
title('Surface plot of z = x * exp( -x^2 - y^2)') % give a title
set(gca,'XTickLabels',linspace(-2,2,3), ... % more about this later
'YTickLabels',linspace(-3,3,3) ) % define tick labels
%
16
87. [zx,zy] = gradient(z,.2,.2); % compute gradient
subplot(122), contour(z), hold on, quiver(zx, zy) % contour
title('Quiver Plot'),
hold off
we obtain the plot shown in Fig. 3.
Surface plot of z = x * exp( −x^2 − y^2)
−2
0
2
−2
−3
0
0.5
0
−0.5
3
5 10 15 20
30
25
20
15
10
5
Quiver Plot
Figure 3: quiver displays angle and magnitude of data.
15 Handle Graphics
Each and every graphics object has a unique identi
88. er and is usually referred
to as a handle, and hence the name HandleGraphics. Current properties of the
graphic object are queried with get command while the properties are de
89. ned
using set. For example, to change the thickness of the the curve y = x2,
x = -2:.01:2;
y = x.^2;
h = plot(x,y),grid
h =
17
90. 81.0007
get(h)
Color = [1 1 0]
EraseMode = normal
LineStyle = -
LineWidth = [0.5]
MarkerSize = [6]
Xdata = [ (1 by 401) ]
Ydata = [ (1 by 401) ]
Zdata = []
ButtonDownFcn =
Children = []
Clipping = on
Interruptible = no
Parent = [72.0017]
Type = line
UserData = []
Visible = on
ans =
[]
set(h,'LineWidth',3)
18
91. 4
3.5
3
2.5
2
1.5
1
0.5
0
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2
Figure 4: Changing properties of a graphic object.
Example 15.1 Inset. A portion of the original plot is displayed in the same
drawing area.
% inset_ex1.m
%
x = -2:.01:2;
y = x.^2 .* sin(1 ./x.^2);
ix = find( x 0.5 x -0.5 ); % pick indices that correspond
% to the interval
hfull = axes % define full screen as plot area
hp = plot(x,y), grid
hins = axes('Position', [0.4,0.5,0.5,0.35]) % new axes origin located
% at 40% of the way
% horizontally and 50% of
% other two parameters indicate
% width and height in normalized
% coordinates
plot( x(ix),y(ix),'g' ) % plot selected values
19
92. 1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
0.2
0.1
0
−0.1
−0.2
−0.3
−0.5 0 0.5
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2
Figure 5: Creating simple inset plots.
Example 15.2 Inset. Interactively select the portion of the plot for inset.
% inset_ex2.m
% use of ginput to locate a portion of the plot for inset
%
x = 0:.01:2;
y = exp(-12*x) .* sin(50*x);
hfull = axes;
plot(x,y)
disp('Select points using the left button on type mouse')
[X,Y] = ginput(2) % pick coords of lower left and top right
XX = [X(1) X(1) X(2) X(2) X(1)]; % define vertices to draw a box around
YY = [Y(1) Y(2) Y(2) Y(1) Y(1)]; % the selected portion
hold % hold the plot to draw the box
plot(XX+i*YY) % draw a box
hi = axes('Position',[0.45,0.55,0.4,0.35]) % define new axes
ix = find( x = X(2) x = X(1) );
plot( x(ix),y(ix) ), grid
20
93. 0.8
0.6
0.4
0.2
0
−0.2
−0.4
0.2
0.1
0
−0.1
−0.2
0.1 0.2 0.3 0.4 0.5
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
Figure 6: The user can select the lower left and top right corners of a box, and
display that portion in another part of the window.
Example 15.3 Area under curve. To
94. ll area under the curve y = f(x), a
x b.
% curvefill_ex1.m
% fill area under a curve
%
x = -2:.01:2;
y = humps(x);
plot(x,y), grid
ix = find( x = 0.5 x = 1.5 );
X = [0.5, x(ix), 1.5];
Y = [0 , y(ix), 0 ];
hp = patch(X,Y,'b');
set(hp,'EdgeColor',[1,0,0]);
21
96. lled polygon whose vertices are given in
X and Y using the colour 'c'. EdgeColor is used to highlight the patch. Note
the
97. ll area for negative values of y.
Example 15.4 Greek letters, superscripts and subscripts in graph annotation.
Note that while it is fairly straight forward to use these functions, it would
be too painful for extensive mathematical type setting using this approach!
% script for greek titles etc.
x = 0:.01:10;
y1 = besselj(0.5,x);
y2 = besselj(1.5,x);
y3 = besselj(2.5,x);
plot(x,y1,x,y2,x,y3), grid
title('J_{nu+1/2}(x) for nu = 0, 1, 2','Interpreter','tex')
xlabel('x')
ylabel('J_{nu+1/2}(x)')
xlabel('x')
22
98. J n + 1/2 (x) for n = 0,1,2
J n + 1/2 (x)
0.8
0.6
0.4
0.2
0
−0.2
−0.4
0 1 2 3 4 5 6 7 8 9 10
x
Figure 8: Greek letters, subscripts, etc. in graph annotation. The default
interpreter is TeX.
16 GUIs
Matlab provides very powerful, yet simple functions to develop attractive Graph-ical
User Interfaces for your applications. Matlab provides eight user interface
objects - checkbox, edit, frame, popupmenu, pushbutton, radiobutton,
slider and text. There are three simple steps to develop a GUI.
1. Choose a user interface(UI) control from the range available.
2. Place it in the Figure window.
3. Optionally de
99. ne a CallBack for the user interface object.
Example 16.1 A simple example. De
100. ne a pushbutton which prints hello to
the screen.
% a simple pushbutton which says hello
%
pb = uicontrol('Style','pushbutton', ...
'Position',[30, 30, 72, 36], ...
'String','PushMe', ...
23
101. Figure 9: A simple pushbutton. When pressed displays 'Hello' in the command
window, and recon
102. gures itself as a quit button.
'CallBack','disp(''Hello ...'')' );
Note that the bottom left corner of the UI object (i.e., pushbutton is placed
in the Figure window at (30,40). Default units are pixels and the origin is at
the bottom left corner of the Figure window. Next we de
103. ne two additional
properties of pushbutton { the text that appears on the button (PushMe), and
what to do when the user presses the button (CallBack). Usually the CallBack
string is a matlab script.
Example 16.2 A pushbutton which recon
105. The CallBack string here is bit more involved. Recall that strings can be
conveniently constructed in Matlab as an array, enclosed within square brackets.
When using continuation marks, you must keep one quoted string per line. In
other words, don't continue a quoted string. If your CallBack string is more
involved than in the present example, you must use a matlab script or function.
Example 16.3 A Colour sampler. This example illustrates the use of collecting
data from other UI components to achieve a desired computation. Three sliders
are used to represent Red, Green and Blue components of the required colour. A
sample patch is shown in the
106. gure.
% Colour sampler - xcolsamp.m
%
% Author: Venkat V S S Sastry
% Date: 7 August 1997
%
% Notes:
% Needs updateP.m which contains the CallBack
%
Xsp = 2; %spacing between objects
Ysp = 2;
sliH = 28; % height of slider
txtH = 28; % text height ( used for labels Red, Green, Blue)
txtW = 30; % text width
valW = 60; % width value labels
valH = txtH; % for now...
pos = get(gcf,'Position');
ll = 3; bl = 40; width = pos(3); height = pos(4)/4;
llFrm = ll; blFrm = bl; frmW = width;
frmH = 3*txtH + 5*Ysp;
p = [0.1 0.35 0.8 0.65];
ha = axes('Position', p );
%
% define the patch
%
x = [0.1 0.9 0.9 0.1];
y = [0.1 0.1 0.9 0.9];
C = [1 1 1];
hP = patch(x,y,C);
axis('off')
%............................
% Frame for three sliders (R,G,B)
25
107. %
p = [ll, bl, frmW, frmH];
frm = uicontrol('Style','frame', ...
'BackgroundColor', [0.15 0.15 0.15], ...
'Position', p );
% red Text
ll = ll + 2*Xsp;
bl = bl + 1.5*Ysp;
p = [ll, bl, txtW, txtH];
redT = uicontrol('Style','text', ...
'String', 'Red', ...
'ForeGroundColor', [1 0 0], ...
'Position', p );
% red Value
pos = get(redT,'Position');
ll = pos(1) + pos(3) + Xsp;
bl = pos(2);
p = [ll, bl, valW, txtH]; % since txtH = valH
redV = uicontrol('Style','text', ...
'Position', p );
%
% Slider for R
%
pos = get(redV,'Position'); % place slider relative to red value label
ll = pos(1) + pos(3) + Xsp;
bl = pos(2);
sliW = frmW - (4*Xsp + txtW + valW); % remaining width in frm is for slider
p = [ll, bl, sliW, sliH];
sliR = uicontrol('Style', 'slider', ...
'Position', p, ...
'Min', 0, 'Max', 1, ...
'CallBack', 'updateP');
% green Text
pos = get(redT,'Position');
ll = pos(1);
bl = pos(2) + pos(4) + Ysp;
p = [ll, bl, txtW, txtH];
grnT = uicontrol('Style','text', ...
'String', 'Green', ...
'ForeGroundColor', [0 1 0], ...
'Position', p );
% green Value
pos = get(grnT,'Position');
ll = ll + txtW + Xsp;
p = [ll, bl, valW, txtH];
26
108. grnV = uicontrol('Style','text', ...
'Position', p );
%
% Slider for G
%
pos = get(grnV,'Position');
ll = pos(1) + pos(3) + Xsp;
% borrow the width of sliR
p = [ll, bl, sliW, sliH];
sliG = uicontrol('Style', 'slider', ...
'Position', p, ...
'Min', 0, 'Max', 1, ...
'CallBack', 'updateP');
% blue Text
pos = get(grnT,'Position'); % place blue text relative to green text
ll = pos(1);
bl = pos(2) + pos(4) + Ysp;
p = [ll, bl, txtW, txtH];
bluT = uicontrol('Style','text', ...
'String', 'Blue', ...
'ForeGroundColor', [0 0 1], ...
'Position', p );
% blue Value
pos = get(bluT,'Position');
ll = pos(1) + txtW + Xsp;
bl = pos(2);
p = [ll, bl, valW, valH];
bluV = uicontrol('Style','text', ...
'Position', p );
%
% Slider for B
%
pos = get(bluV,'Position');
ll = pos(1) + pos(3) + Xsp;
bl = pos(2);
% borrow sliW from the previous sliders
p = [ll, bl, sliW, sliH];
sliB = uicontrol('Style', 'slider', ...
'Position', p, ...
'Min', 0, 'Max', 1, ...
'CallBack', 'updateP');
%
% Quit button
27
109. Figure 10: Colour sampler. Adjust the values the Red, Green and Blue compo-nent
using the sliders. A sample of the colour is shown as a patch.
%
pos = get(gcf,'Position');
bWidth = 40; bHeight = 30;
ll = pos(3) - bWidth - Ysp; bl = 2;
p = [ll, bl, bWidth, bHeight];
qBut = uicontrol('Style','pushbutton', ...
'Position', p, ...
'String', 'Quit', ...
'CallBack', 'delete(gcf)');
Example 16.4 A CallBack embedded in the same function. This is a con-
venient technique to organize the GUI code. De
110. ne a function which handles
all major events. The function is normally with one argument, say, action.
Branch to appropriate segment depending on the action. The following code
illustrates this technique. At the start, a push button is placed along with in-
formative text. The button's callback is to move the button to another location,
when pressed. This is achieved by invoking xgui2('move').
28
111. % xgui2.m
% simple demonstration of embedding CallBacks in the
% same function
function xgui2(action);
if nargin 1,
action = 'start';
end;
if strcmp(action,'start'),
% place a button
bW = 0.2; bH = 0.15;
set(gcf,'Units', 'normalized');
bh = uicontrol('Style','pushbutton', ...
'Units','normalized', ...
'Position',[0.1 0.2 bW bH], ...
'String', 'PushMe', ...
'CallBack', 'xgui2(''move'')' );
txt = uicontrol('Style','text', ...
'Units','normalized', ...
'Position', [0.01, 0.9, 0.9 0.1], ...
'String', ...
'First click in the window, and Press button to watch it move there.');
elseif strcmp(action,'move'),
disp('Moving ...bh')
bh = gco;
pos = get(bh, 'Position');
bW = pos(3); bH = pos(4);
ptr = get(gcf,'currentpoint');
x = ptr(1); y = ptr(2);
set(bh,'Position', [x y bW bW])
% delete(bh)
end
29
112. Figure 11: Playing with buttons. Demonstrates the use of embedding the Call-
Backs within the same function.
17 Obtaining Hard Copy
Both numerical and graphical output from MATLAB can be stored for future use.
To store your MATLAB interaction, issue the command
diary output
and subsequent output from MATLAB is written to the
113. le output in your sub-directory.
This facility can be turned o by issuing diary o or simply diary.
The diary toggles between on, o values.
Graphical output can be redirected to a suitable plotter or laser printer.
Having generated the required plot, type print at the MATLAB prompt. The
output goes to the default printer. For saving the plot in various graphics
115. 18 MATLAB Quiz
1. What is the MATLAB prompt?
2. What is the command to leave the system?
3. Does ^C leave the system?
4. Is MATLAB case sensitive?
5. What is the terminator for MATLAB commands?
6. What is the command to read data from the terminal?
7. Given x = [2 1 0 1 2], what is the result of the command i = (x = 0)?
8. What is the operator for point-wise multiplication?
9. If A and B are matrices what do the commands | AB and A=B rep-resent?
10. How do you invoke a text editor while you are in MATLAB ?
11. If Y is a matrix, what does plot(Y) do ?
12. How do you invoke a user de
116. ned function xyz.m?
13. If x = [1 0 1] and y = [0 1 1], what is the result of x : y ?
14. What happens if you try x y ?
15. How do you store MATLAB interaction?
16. If A and B are matrices, is the statement A = B legal? If so, what is
returned by such a statement?
17. Typing pi at MATLAB prompt displays the number, 3:1416. What is the
command to display the available decimals?
18. Can you call programs written in FORTRAN or C?
31
118. ne the vector x = (3;4; 2; 1; 0; 2; 3; 5; 10) (Remember to use
matlab syntax). What is returned by the following MATLAB com-mands?
i. length(x)
ii. max(x)
iii. size(x)
iv. x(12) = x(3)
v. A. L = (x = 2),
B. L = (x 3);
C. L = (x 4 x 4).
vi. Generate the row vector (1;0:75;0:5;0:25; 0:0; 0:25; 0:5; 0:75; 1:0).
vii. What is the output of the command k = linspace(-1,1,5)?
(b) De
119. ne the matrix A =
1 0 6 3
1 2 0 2
0 3 1 2
6 0 0 1
. Observe the response
of the following commands.
i. size(A)
ii. det(A)
iii. inv(A),eig(A) and [V,D] = eig(A)
iv. A(:; 2);A(1 : 3; 2 : 4) and A(:)
v. max(A), max( max(A) )
vi. i =
120. nd( A == max( max(A) ) )
vii. P = poly(A) and roots(P) .
(c) Given A =
1 2 3
4 5 6
7 8 0
and b =
1
3
5
, solve the system Ax =
b.
For the above matrix, what is returned by [L;U] = lu(A)?
2. What is returned by the following commands?
rand(6),rand(1,6),ones(6),ones(2,6),zeros(6),zeros(4,6)
3. If A =
i 1 + i i
0 1 1
1 0 0
, what is returned by eye( size(A) ),ones( size(A)
) and zeros( size(A) )?
4. Write the MATLAB commands to perform the following calculations.
32
121. y
1
6
y = 1 + x y = 1 x
-2 -1 0 1 2 x
-
Figure 12: Triangular hat function
(a) to extract the indicated (elements are shown in boldface) submatrix
of A =
1 2 3
4 5 6
7 8 9
.
(b) to
135. 6. Case Study | Nonlinear Pendulum
The equation of motion of a strongly damped simple pendulum is given
by
+ 0:3 _ + sin = 0
Subject to the initial conditions
(0) =
4
_(0) = 0
simulate the motion of the pendulum for the
136. rst 15 seconds. Experiment
using ode23 and ode45 and plot your results. The quantity
= ln
x1
x2
where x1 and x2 are any two successive amplitudes is called logarithmic
decrement. With the help of the plot you have generated and using ginput
command estimate the logarithmic decrement.
[Hint: Use the help facility for the syntax of relevant commands. The above
second order dierential equation can be expressed as a system of two
137. rst
order dierential equations as shown below.
x_1 = 0:3 x1 sin x2
x_2 = x1
]
7. Case Study | Population Growth2
Let Fi and Ci denote number of foxes and chicken at a time step i. At
the next time step these population are related by the equations
Fi+1 = 0:6Fi + 0:5Ci
Ci+1 = kFi + 1:2Ci
where k represents the kill rate of chicken by foxes. Starting with the
initial population as F1 = 100 and C1 = 1000, the above equations can be
used to model the two populations at subsequent time step.
In the matrix notation, the above equations read
xi+1 = Axi for i = 1; 2;
where xi =
(
Fi
Ci
)
, A =
(
0:6 0:5
k 1:2
)
and x1 =
(
100
1000
)
.
2With due acknowledgements to Ben Noble and James W Daniel, Applied Linear Algebra,
Prentice-Hall, 1988, ISBN: 0-13-593609-8.
34
138. Hence,
x2 = Ax1
x3 = Ax2
= AAx1
= A2x1 etc.
In general
xi+1 = Aixi for i = 0; 1;
(a) For a low kill rate of k = 0:1
139. nd the two populations. Plot the
results. Do the populations reach an equilibrium?
(b) For a high kill rate of k = 0:18
140. nd the two populations. Plot the
results. Do the populations reach an equilibrium?
(c) For an intermediate kill rate of k = 0:16
141. nd the two populations.
Plot the results.
The behaviour of the population size is closely related to how the ma-trix
powers i.e Ai behaves for large i, which in turn is dictated by the
eigenvalues of the matrix.
Find the eigenvalues for the above three cases. Can you suggest a condition
under which Ai goes to 0 as i ! 1.
35
142. 20 Model Answers for Tutorial Sheet
1. Basic Commands
(a) Enter it as
x = [-3 -4 2 1 0 2 3,5,10]
i. length(x) returns 9
ii. max(x) returns 10
iii. size(x) returns the vector [1 9]
iv. returns the vector
-3 -4 2 1 0 2 3 5 10 0 0 -2
Note the additional two zeros after 10.
v. A. L = (x=2) returns the 0-1 vector
0 0 1 0 0 1 1 1 1 0 0 0
B. L = (x3) returns the vector
1 1 1 1 1 1 0 0 0 1 1 1
C. L = (x4 x -4) returns the vector
1 0 1 1 1 1 1 0 0 1 1 1
vi. xx = -1:0.25:1 will generate the required sequence.
vii. returns the vector
-1.0000 -0.5000 0 0.5000 1.0000
(b) Enter the matrix as
a = [1 0 6 -3; -1 2 0 2;0 3 -1 -2;-6 0 0 1]
i. size(a) returns the vector [4 4].
ii. det(a) returns the scalar 376.
iii. inv(a) returns the matrix
-0.0053 0.0479 -0.0319 -0.1755
0.0293 0.2367 0.1755 -0.0346
0.1516 0.1356 -0.0904 0.0027
-0.0319 0.2872 -0.1915 -0.0532
eig(a) returns the vector
-3.0636 + 2.9004i
-3.0636 - 2.9004i
4.5636 + 0.5475i
36
143. 4.5636 - 0.5475i
[V,D] = eig(a) returns two matrices
V =
-0.5175 - 0.1981i -0.5175 + 0.1981i -0.3849 + 0.0609i -0.3849 - 0.0609i
-0.0452 + 0.1542i -0.0452 - 0.1542i 0.5682 - 0.2991i 0.5682 + 0.2991i
0.2623 - 0.3935i 0.2623 + 0.3935i 0.0747 - 0.0977i 0.0747 + 0.0977i
-0.3679 - 0.5551i -0.3679 + 0.5551i 0.6178 - 0.1974i 0.6178 + 0.1974i
D =
-3.0636 + 2.9004i 0 0 0
0 -3.0636 - 2.9004i 0 0
0 0 4.5636 + 0.5475i 0
0 0 0 4.5636 - 0.5475i
Note that the eigenvector are placed along the diagonal of D.
iv. a(:,2) returns the column vector (0,2,3,0)
a(1:3,2:4) returns the submatrix
0 6 -3
2 0 2
3 -1 -2
a(:) returns the complete matrix as a column vector.
v. max(a) returns the vector
1 3 6 2
where each element corresponds to the maximum element for each
column.
max( max(a) ) returns the scalar 6 which is the maximum element in
the matrix.
vi. returns the location of the maximum element treating the matrix as
a single column. You have to do extra work to express that number
on matrix 'i,j' notation.
vii. poly(a) returns the coecients of the characteristic polynomial of ma-
trix a. The coecients are ordered from highest degree to the lowest.
viii. roots(poly(a)) returns the eigenvalues of a
-3.0636 + 2.9004i
-3.0636 - 2.9004i
4.5636 + 0.5475i
4.5636 - 0.5475i
37
144. (c) Remember to use the column vector for b. Use x = ab which returns the
column vector
x =
0.3333
0.3333
0.0000
[L,U] = lu(a) returns
L =
0.1429 1.0000 0
0.5714 0.5000 1.0000
1.0000 0 0
U =
7.0000 8.0000 0
0 0.8571 3.0000
0 0 4.5000
2. rand(6) returns a 6 by 6 matrix of random elements which are uniformly dis-
tributed in the interval 0.0 to 1.0.
rand(1,6) returns a row vector of six columns.
ones(6) returns a 6 by 6 matrix whose elements are all 1.
ones(2,6) returns a 2 by 6 matrix whose elements are all 1.
zeros(6) returns a 6 by 6 matrix whose elements are all zero.
zeros(4,6) returns a 4 by 6 matrix whose elements are all zero.
3. Remember to clear i.
eye(a), ones(a), zeros(a) return an identity matrix, a matrix of 1's and a matrix
of zeros of size a respectively.
4. Remember to clear the matrix a.
(a) to extract the submatrix consisting of rows two through three and columns
two through three, use a(2:3,2:3).
(b) maximum element is given by max(max(a)). Note that a == max(max(a))
returns a matrix with 1 in the location where the logical expression is true.
(c) [i,j] = find( a == max(max(a) ). See help find for further details
(d) A possible matlab function could be de
145. ned as
function a = bandm(n,dentry,sup,sub),
for i=1:n,
for j = 1:n,
38
146. if i==j,
a(i,j) = dentry;
elseif ( j i j = i+sup),
a(i,j) = - 1;
elseif ( i j i = j+sub),
a(i,j) = - 1;
end
end
end
where n is the matrix size, dentry is the diagonal entry, sup and sub
indicate the number of super/sub diagonals.
(e) Use det(b) which is 5. To verify the conjecture, you may proceed as
for k = 1:10,
d = det( bandm(k,2,1,1) );
s = sprintf(' matrix size n = %3d t determinant is %4d', k,d);
disp(s),
end
matrix size n = 1 determinant is 2
matrix size n = 2 determinant is 3
matrix size n = 3 determinant is 4
matrix size n = 4 determinant is 5
matrix size n = 5 determinant is 6
matrix size n = 6 determinant is 7
matrix size n = 7 determinant is 8
matrix size n = 8 determinant is 9
matrix size n = 9 determinant is 10
matrix size n = 10 determinant is 11
(f) Use [v,d] = eig(b)
(g) Enter the following in a
147. le called t4g.m
function y = t4g(x)
y = 1 ./(x.^2 - 1) + 2;
The important thing to note in here is the operator ./ and the preceding
space! Invoke the function as t4g(x).
(h) Use plot(x,t4g(x)).
(i) Use fzero('t4g',0.5) which returns 0.7071. The other zero is symmet-
rically placed with respect to the y-axis.
(j) Use roots([1 -6 -72 -27]). Note that the coecients are entered start-
ing with that of the highest degree. If a particular coecient is absent,
remember to enter zero.
5. This requires patience and thorough understanding of MATLAB syntax. The
following scripts do the job:
39
148. (a) This uses logical indexing.
function y = triang(x)
xl0 = x( x-1 );
xr0 = x( x1 );
xl = x( x=-1 x0 );
xr = x( x=0 x=1 );
y = [zeros( size(xl0) ) 1+xl 1-xr zeros( size(xr0) )];
(b) A variation on logical indexing but involves more computation (Due to Mr.
Richard Norgate).
function y = hat(x);
y=(-1x).*(x0).*(x+1)+(0=x).*(x1).*(1-x);
end
(c) and yet another compact de
149. nition below:
function y = triang3( x ),
y = max( min( (x+1), (1-x) ), 0 );
6. First de
151. rst order system as
% Simple Harmonic Motion --- with damping.
function ydot = shm(t,y)
ydot(1) = -0.3*y(1) -9.8*sin( y(2) );
ydot(2) = y(1);
ydot = ydot'; % you need to return a column
in a
152. le called shm.m. Invoke ode23 as
t0 = 0;
tfinal = 20;
tspan = [t0 tfinal];
y0 = [0 0.25];
[t y] = ode23(@shm,tspan,y0);
plot(t,y), grid
[X,Y] = ginput(2) % you need to two successive points
delta = log( Y(1)/Y(2) ) % amplitudes are stored in the matrix Y
Depending on steadiness of your hand delta is around 0.2992 using the
153. rst two
peaks.
7. You can use the following script as a guideline. Adopt the code as necessary.
Feel free to add bells and whistles, if you wish!
% population of fox and chicken (geese, if you wish!)
% set the value of k befor invoking this script
%
clear a;
40
154. a = [0.6 0.5; -k 1.2];
xini = [100 1000];
%
pop = [xini'];
xold = xini';
for i = 1:20,
xtemp = a*xold;
xold = xtemp;
pop = [pop, xtemp];
end
plot(pop') % and they live happily ever after!
% redefine k to be 0.18 and rerun the script
% they want to lead their separate lives!
%
% k Eigenvalues
%
% 0.1 [0.7 1.1]
% 0.18 [0.9 0.9]
% 0.16 [0.8 1.0]
% 0.2 ...
The eigenvalues of the matrix are:
p
9 50 k
100
90 10
(1)
41
155. 21 Common tasks in MATLAB
This section lists a number of examples describing how you can put matlab to
best use for solving typical problems one encounters.
Example 21.1 Generate a
156. xed sequence of numbers in an interval. To gener-
ate a sequence in the interval [2; 2] with a step size of 0.1, and store the result
in a vector, say, x.
x = -2:.5:2
x =
Columns 1 through 7
-2.0000 -1.5000 -1.0000 -0.5000 0 0.5000 1.0000
Columns 8 through 9
1.5000 2.0000
Example 21.2 Generate a uniformly distributed random sequence of numbers
in an interval.
rand function generates the required numbers in the interval. Map these numbers
to the desired interval. The following linear function
f(x) : [a; b] ! [u; v] (2)
where
f(x) =
(u v)
(a b)
x +
(va ub)
(a b)
(3)
may be used for the map.
For generating uniformly distributed random numbers in the interval [2; 2],
157. rst generate the numbers in the interval [0; 1], and then map them using f(x) =
2 + 4x. Thus,
x = -2 + 4*rand(1,5)
x =
-0.4491 -0.0010 -1.4099 0.3487 1.3823
Example 21.3 Timing and Operational Count. In computing two measures
are very important { how much time does my code take and how many
oating
point operations does it require.
Computation of the above two measures are illustrated for matrix multipli-cation
using the code below:
42
158. % tmult.m
% time for matrix multiply
%
ns = [10, 50, 100, 500, 1000];
stats = [];
disp('timing - matrix multiply')
for k = 1:length(ns),
n = ns(k);
a = rand(n); b = rand(n);
tic
a*b;
et = toc; % save the elapsed time
data = sprintf('%d t %g', n, et);
stats = str2mat(stats,data); % can form the matrix this way ONLY
end
stats
A typical run on my PC produced the following output:
timing - matrix multiply
stats =
10 0.000448636
50 9.28326e-05
100 0.000293572
500 0.0134731
1000 0.0998544
Matrix multiplication counts 2N3
ops for an N N matrix. So watch out
before you run this script for very large matrices! sprintf is convenient to format
items, and to accumulate statistics I need to convert them to a matrix of strings
as each string may be of dierent size. Note also that these measurements can
vary from run to run and should be treated with caution.
More reliable timing measurements can be obtained using timeit function
available on MathWorks File Exchange. Here is the sample output from timeit.
% tmult2.m
% time for matrix multiply
%
ns = [10, 50, 100, 500, 1000];
stats = [];
disp('timing - matrix multiply')
for k = 1:length(ns),
n = ns(k);
a = rand(n); b = rand(n);
43
159. f = @ a*b;
T=timeit(f);
data = sprintf('%5d t %g', n, T);
stats = str2mat(stats,data);
end
stats
Sample output:
tmult2
timing - matrix multiply
stats =
10 5.21495e-06
50 2.56593e-05
100 0.00011701
500 0.0131794
1000 0.107918
Example 21.4 Passing a parameter to function. Consider a situation where
you are interested in determining the root of a continuous function. This func-
tion involves a parameter, and you are interested
160. nding the root for various
values of this parameter.
Find the roots of
J0(x) +
J2(x)
x2 = 0 (4)
for varying from 0 to 10.
Equation 4 arises in determining the natural frequencies of a hemispherical
drum.
The parameter is passed to the matlab function via global as
% drum.m
function y = drum(x)
global ALPHA
y = besselj(0,x) + ALPHA * besselj(2,x)./x.^2;
Now the following script will compute the roots for = 0; 2; 4; 6; 8 and 10.
%File: sdrum2.m
% Passing additional parameter to fzero
% using function handles
alfs = [0, 2 4 6 8 10];
44
161. xini = 2.0; % hope this guess would do
res = [];
for k = 1:length(alfs)
ALPHA = alfs(k);
F = @(x) besselj(0,x) + ALPHA * besselj(2,x)./x.^2;
xroot = fzero( F,xini);
res = [res;ALPHA, xroot]; % store the pair
end
disp('natural frequencies - hemispherical drum')
disp(' ')
res
The approximations are
natural frequencies - hemispherical drum
res =
0 2.4048
2.0000 2.6736
4.0000 2.9108
6.0000 3.1230
8.0000 3.3143
10.0000 3.4874
Example 21.5 Evaluation of series. This is a typical problem. Consider sum-
ming the series
loge(1 + x) = x x2
2
+
x3
3
+ ()k+1 xk
k
(5)
Starting with the initial term, we keep adding until the inclusion of the addi-tional
term no longer improves the partial sum. You need to be careful about
scalar or vector arguments.
45
162. scalar version vector version
% File: sseries.m
% summation of series - for log(1+x)
function y = sseries(x),
tsum = x;
term = x;
k = 1;
while( tsum+term ~= tsum )
ratio = (-1)*(x*k) /(k+1);
term = term*ratio;
tsum = tsum + term;
k = k + 1;
end
y = tsum;
% File: vseries.m - summation of series - for % vectorized version - x is a row
function y = vseries(x),
tsum = x; % vector
term = x; % vector
k = 1;
while( norm(tsum+term) ~= norm(tsum) )
ratio = (-1)*(x*k)./(k+1); % note ./
term = term.*ratio; % note .*
tsum = tsum + term;
k = k + 1;
end
y = tsum;
Sample output comparing with matlab intrinsic function are shown below:
sseries(0.2)
ans =
0.18232155679395
log(1.2)
ans =
0.18232155679395
vseries([0.2 0.4 0.5])
ans =
0.18232155679395 0.33647223662121 0.40546510810816
log([1.2 1.4 1.5])
ans =
0.18232155679395 0.33647223662121 0.40546510810816
Example 21.6 Solution of iterations. Consider the following iteration
xn+1 = 1 +
1
xn
(6)
with x0 = 2. Let us stop the iterates when jxn+1 xnj 0:0005.
Let us write the function which accepts two input arguments { an initial
guess and a tolerance limit to check for convergence. If tolerance is not given,
we will use the machine epsilon. The return value for the function is a vector
consisting of intermediate iterates. This is handy if you want to plot them. Here
is the code.
46
163. % iterations - iters.m
% INPUT
% x0 = starting value
% ep = error control; default is machine epsilon
% OUTPUT
% its = intermediate iterates
%
function its = iters(x0, ep),
if nargin 2, ep = eps; end
xnow = x0;
xnext = 1 + 1/xnow ;
its = [xnow, xnext];
while ( abs(xnext - xnow) ep )
xnow = xnext;
xnext = 1 + 1/xnow;
its = [its, xnext];
end
Sample output is shown below:
its = iters(2,0.0005)
its =
Columns 1 through 4
2.00000000000000 1.50000000000000 1.66666666666667 1.60000000000000
Columns 5 through 8
1.62500000000000 1.61538461538462 1.61904761904762 1.61764705882353
Columns 9 through 10
1.61818181818182 1.61797752808989
its = iters(2)
its =
Columns 1 through 4
2.00000000000000 1.50000000000000 1.66666666666667 1.60000000000000
... some output omitted ...
Columns 33 through 36
1.61803398874991 1.61803398874989 1.61803398874990 1.61803398874989
Columns 37 through 38
1.61803398874990 1.61803398874989
Example 21.7 Solution of system of non-linear equations. Consider the sys-
tem
x2 + y2 = 4 (7)
xy = 1 (8)
47
164. starting with an initial guess x = [3;1]′.
We are going to use function fsolve from Optimization Toolbox. First, de
165. ne
the system of non-linear equations in a function
166. le called sys.m as
% system of nonlinear equations
%
function f = sys(x),
f(1) = x(1)^2 + x(2)^2 - 4;
f(2) = x(1)*x(2) - 1;
Now invoke fsolve as
x = [3;-1];
xs = fsolve( @sys,x )
xs =
1.93185213259533
0.51763801981797
Note that these routines are fairly sensitive to initial approximations. This
particular example can be converted into a higher order polynomial. Using
second of the equations 8, namely y = 1=x in the
167. rst, we immediately obtain
x4 4x2 + 1 = 0. Now using roots, we have all the four roots.
roots([1 0 -4 0 1])
ans =
1.93185165257814
-1.93185165257814
0.51763809020504
-0.51763809020504
So be prepared to do some mathematics before you lunge into MATLAB!
Example 21.8 Working with inputs which are user-de
168. ned functions. Quite
often we need to work with function inputs to function. A typical example is
implementing Newton-Raphson's method in matlab. One normally de
170. les. How do you capture their
values at a speci
171. c point? feval comes to our rescue.
Recalling Newton-Raphson's method
xn+1 = xn f(xn)
f′(xn)
(9)
The following code illustrates this approach. Note that the stopping criteria
is by no means sophisticated.
48
172. % Newton-Raphson method - nr.m
%
function [x, fx, fdx, its] = nr(fun,deriv,x0, tol)
if nargin 4, tol = 1.0e-4; end
xini = x0;
its = [x0];
fx = feval(fun,xini);
fdx = feval(deriv, xini);
step = fx/fdx;
while ( abs(step) tol )
xnext = xini - step;
its = [its, xnext];
xini = xnext;
fx = feval(fun,xini);
fdx = feval(deriv, xini);
step = fx/fdx;
end
x = xnext;
fx = feval(fun,x);
fdx = feval(deriv,x);
For example, to determine zero of the function exp(x) x = 0, de
174. le as
%nrex1.m
function y = nrex1(x),
y = exp(-x) - x;
% nrex1d.m
function y = nrex1d(x),
y = - exp(-x) - 1;
Now invoke the nr-function as
[z,fx,fdx,its] = nr(@nrex1,@nrex1d,0.1,1.0e-08)
z =
0.56714329040978
fx =
2.220446049250313e-16
fdx =
-1.56714329040978
49
175. its =
Columns 1 through 4
0.10000000000000 0.52252289377317 0.56677815778619 0.56714326628276
Column 5
0.56714329040978
You can con
176. rm this result by running nr with dierent tolerances.
Example 21.9 Passing auxiliary parameters. Some of the matlab function ac-
cept additional parameters to be passed to the function they use. Consider ap-
proximating the following integral, using the built-in function integral.
∫ 1
0
xk ex−1 dx (10)
for k = 20.
First we de
177. ne a function handle with the parameter as
% File: xint1.m
k = 20;
F = @(x,k) x.^k.*exp(x-1);
and invoke integral with another anonymous function that calls F(x,k).
q = integral( @(x) F(x,k) , 0,1, 'AbsTol', 1.0e-8)
q =
0.045544886223981
To generate a table for various k,
%File: xint2.m
F = @(x,k) x.^k.*exp(x-1);
fprintf(' k q1 n');
for k = 1:2:20,
q = integral( @(x) F(x,k) , 0,1, 'RelTol', 1.0e-2);
fprintf(' %3d %18.12f n', k, q)
end
% sample output
xint2
k q1
50
178. 1 0.367879441171
3 0.207276647029
5 0.145532940573
7 0.112383504069
9 0.091612292990
11 0.077352228863
13 0.066947702576
15 0.059017540879
17 0.052771119169
19 0.047722755796
Incidentally, this is a notorious integral, if you decide to use recursion via Ik =
1 kIk−1 with i0 = 1 1=e. Using recursion, there is no way to achieve any
signi
180. 22 Worked Examples in Programming
This section contains several worked examples in MATLAB programming.
Example 22.1 How many random numbers (uniformly distributed pseudoran-
dom numbers, using rand function) are required to make a sum not exceeding
10?
1 % File: how_many_rands_1.m
2 % Number of rands that add up to a sum not exceeding 10
3 n = 0;
4 tot = 0;
5
6 while ( tot = 10 )
7 x = rand(1);
8 tot = tot+x;
9 n = n+1;
10 end
11 if ( tot 10 )
12 tot = tot - x;
13 end
14 fprintf(' Total: %.3fn', tot)
15 fprintf('Required rands: %5dn', n)
Here is a sample output.
how_many_rands_1
Total: 9.966
Required rands: 22
Example 22.2 Local Maxima. Hunting for Gold! Infrared reading of
a portion of desert where gold is believed to be present are given by the mea-
surements presented in the matrix. The boundaries of the a gold reef, based
on readings that are greater than the average of those around them. One such
neighbourhood is de
181. ned as 4-neighbourhood takes the average of elements in N,
S, E and W of each element of the array of measurements. For simplicity, we
compute these averages starting at element (2,2) and stopping one short of the
last column and last row.
Your task is to produce a matrix M of same size as that of A that contains
1 where the value exceeds the average of elements in 4-neighbourhood.
A =
21 21 22 30 40 21 34 45
21 22 23 30 45 21 37 40
22 23 24 45 46 47 38 39
22 23 24 35 46 47 38 38
23 24 25 36 46 49 37 36
23 24 25 37 39 48 36 35
23 24 25 25 26 25 26 25
23 25 26 27 28 29 30 31
52
182. We loop through the rows and columns with the help of two loops. Every
time we visit an element, we access the elements of 4-neighbourhood and see if
the current element is a relative maximum (Lines 21 - 26). The complete code
is shown below.
1 %File: relmax1.m
2 % relative maximum of array of elements
3 % an element is deemed rel max if it is greater than the average of
4 % elements in NSEW positions
5 %
6 A =[21 21 22 30 40 21 34 45;
7 21 22 23 30 45 21 37 40;
8 22 23 24 45 46 47 38 39;
9 22 23 24 35 46 47 38 38;
10 23 24 25 36 46 49 37 36;
11 23 24 25 37 39 48 36 35;
12 23 24 25 25 26 25 26 25;
13 23 25 26 27 28 29 30 31];
14 M = zeros( size(A) );
15
16 [r,c] = size(A);
17 % extract the elements of a submatrix using the mask
18 for i = 2:c-1
19 for j = 2:r-1
20 x = A(i,j);
21 loc_avg = ( A(i-1,j) + A(i,j-1)+ A(i,j+1)+A(i+1,j) )/4;
22
23 if ( x loc_avg ),
24 % local max
25 M(i,j) = 1;
26 end
27 end
28 end
Sample output is given below.
M
M =
0 0 0 0 0 0 0 0
0 0 0 0 1 0 1 0
0 1 0 1 1 1 0 0
0 0 0 0 1 1 0 0
0 1 0 1 1 1 0 0
0 0 0 1 0 1 0 0
0 0 0 0 0 0 0 0
53
183. 0 0 0 0 0 0 0 0
Example 22.3 Summing series. An approximation to is given by the series
2 8
16
=
∞Σ
k=1
1
(2k 1)2(2k + 1)2 :
How accurate is the sum of 1000 terms?
Noticing that the denominator in the terms of the series are product of odd
integers, we chnage the summation index to
t n. As k = 1; 2; 3; , n runs through 1; 3; 5; . Two approaches are shown
below - one using straight forward for loop, and another using array operations.
The time info will dier from run to run.
1 %% A series approximation to $pi$
2 %
3 %
4 % $$frac{pi^2-8}{16} = sum_{n=1}{infty}; frac{1}{(2n-1)^2(2n+1)^2$$
5 %
6 t0 = tic;
7 N = 1000;
8 total = 0;
9 for n = 1:2:N,
10 term = 1/( (n*n)*(n+2)*(n+2) );
11 total = total + term;
12 end
13 pi_approx = sqrt( 16*total + 8 );
14 tf = toc(t0);
15 fprintf(' Method 1n');
16 fprintf(' Number of terms, N: %dn', N);
17 fprintf(' an approximation to pi: %.12fn', pi_approx);
18 fprintf(' abs. error (pi - pi_approx): %.12fn', abs(pi-pi_approx));
19 fprintf(' elapsed time: %.6fn', tf);
20
21 %% method 2
22 %
23 %n = [N-1:-2:1];
24 t0 = tic;
25 n=[1:2:N];
26 terms = 1 ./( n.*n.*(n+2).*(n+2) );
27 total2 =sum( terms );
28 pi_approx2 = sqrt( 16*total2 + 8 );
29 tf = toc(t0);
30 fprintf(' Method 2n');
31 fprintf(' Number of terms, N: %dn', N);
54
184. 32 fprintf(' an approximation to pi: %.12fn', pi_approx2);
33 fprintf(' abs. error (pi - pi_approx): %.12fn', abs(pi-pi_approx2));
34 fprintf(' elapsed time: %.6fn', tf);
Sample output from the program is shown below.
series_pi_1
Method 1
Number of terms, N: 1000
an approximation to pi: 3.141592653167
abs. error (pi - pi_approx): 0.000000000423
elapsed time: 0.000050
Method 2
Number of terms, N: 1000
an approximation to pi: 3.141592653167
abs. error (pi - pi_approx): 0.000000000423
elapsed time: 0.000041
Example 22.4 Guessing Game. The computer chooses a random integer
as R = ceil(100*rand(1). Your task is to guess the number which can be
entered with the command x = input('Give me an integer betwenn 1 and
100:');. Display also the number of attempts the user has taken.
This is good example for using while loop as we do not know a priori how
many attempts the user may take. When using this type of while loop, do
make sure that you break out of them.
1 % File: guess1.m
2 %% Guessing game - use of while
3 %
4
5 num = ceil(100*rand(1));
6 x = input('Give me an integer betwenn 1 and 100:');
7 nAttempts = 1;
8 while( 1 )
9
10 if ( x num )
11 disp('...hot ... lower')
12 x = input('Give me an integer betwenn 1 and 100:');
13 nAttempts = nAttempts+1;
14 elseif ( x num )
15 disp('...cold ... higher')
16 x = input('Give me an integer betwenn 1 and 100:');
17 nAttempts = nAttempts+1;
18 else
19 disp('Bingo ...you got it!')
55
185. 20 fprintf('You got it in %d attempts.n', nAttempts);
21 break
22 end
23
24 end
Here is the sample output.
guess1
Give me an integer betwenn 1 and 100:65
...hot ... lower
Give me an integer betwenn 1 and 100:37
...cold ... higher
Give me an integer betwenn 1 and 100:51
...hot ... lower
Give me an integer betwenn 1 and 100:44
...cold ... higher
Give me an integer betwenn 1 and 100:47
...cold ... higher
Give me an integer betwenn 1 and 100:49
...cold ... higher
Give me an integer betwenn 1 and 100:50
Bingo ...you got it!
You got it in 7 attempts.
Example 22.5 Temperature data for central England. The data set consists of
monthly averages of temperature since 1659 to July, 2014. The data set can be
obtained http://badc.nerc.ac.uk upon request. First few lines are shown below
MONTHLY MEAN CENTRAL ENGLAND TEMPERATURE (DEGREES C)
1659-1973 MANLEY (Q.J.R.METEOROL.SOC., 1974)
1974ON PARKER ET AL. (INT.J.CLIM., 1992)
PARKER AND HORTON (INT.J.CLIM., 2005)
JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC YEAR
1659 3.0 4.0 6.0 7.0 11.0 13.0 16.0 16.0 13.0 10.0 5.0 2.0 8.83
1660 0.0 4.0 6.0 9.0 11.0 14.0 15.0 16.0 13.0 10.0 6.0 5.0 9.08
1661 5.0 5.0 6.0 8.0 11.0 14.0 15.0 15.0 13.0 11.0 8.0 6.0 9.75
1662 5.0 6.0 6.0 8.0 11.0 15.0 15.0 15.0 13.0 11.0 6.0 3.0 9.50
...
2014 5.7 6.2 7.6 10.2 12.2 15.1 17.7 14.9 -99.9 -99.9 -99.9 -99.9 -99.99
Note that the data that is not available is shown as -99.99.
Your task is to write a function getYearMonth( W, condStr ) that accepts
the weather data as a matrix W, and an inequality such as 19 as a string, and
returns the year(s), and month(s) for which the inequality is satis
187. [ys,ms] = getYearMonth( W,19 )
r =
325
348
337
c =
7
7
8
The required code is shown below.
1 function [ys,ms] = getYearMonth( W, condStr )
2 WW = W(:,2:13);
3 cmdStr = ['[ys,ms] = find( WW', condStr, ' );' ]
4 eval( cmdStr );
Note how the variable cmdStr is generated by concatinating the input string
condStr with the appropriate find command.
Example 22.6 Write a program that counts the number of elements that are
in the interval [0; 0:1]; [0:1; 0:2]:::; [0:9; 1:0) in the matrix A = rand(100,100).
Display the counts as a bar chart.
Does the result match with your expectations?
One way approaching the problem is through a simple for loop. The basic
counting is done through counting the one's generated by the logical AL
A=U.
The code is shown below.
1 % File: bincounts.m
2 %
3 A = rand(100,100);
4 L = 0.0; U=0.1;
5 for k = 1:10
6 c(k) = sum(sum( AL A=U));
7 L = U; U=U+0.1;
8 end
9 bar( c )
Example 22.7 Marks obtained in an online assessment for agroup of students
are stored in a
189. # Marked by proc0.pl on Mon Apr 26 10:01:23 2010
#
Name: Svaqynl_F
Student ID: 091106
Syndicate: D5
q1.1::70::0.48::0
q1.2::55::0.70::0
.
.
.
q40.8::a::b::0
q41.1::a::a::1
q41.2::b::b::1
q41.3::_NA_::c::0
Response to a question is represented in the form
1 2 3 4
qid::text|nums::text|nums::mark
where the second
193. led is the mark awarded to the
question.
These marked
194. les are stored in a directory with the extension .mkd.
The marked
195. les are of the form Senfre_NE_000684_O6_75369.mkd. First
group of characters joined by refer to the name and initials of the student.
Your task is to process these
196. les and generate a report of total marks for
each student. Your report should be of the form
Sbena_ZQ = 100.00
Sbzrf_PW = 82.50
Senfre_NE = 102.00
Sevfxarl_PC = 78.50
Sneguvat_Hyphen_Tnyr = 73.50
Snjfvgg_WP = 76.50
Svaqynl = 71.00
Svfure_QW = 85.00
Svryq = 79.50
Note that total marks in this exam add up to a maximum of 120.
The complete program is shown below.
1 %File: getMarks1.m
2 % - Prepare marks sheet
3 % Format question response line
58
197. 4 % qid::text|nums::text|nums::mark
5 % line = 'q1.1::0.48::0.48::2';
6
7 files = dir('*.mkd');
8
9 for k = 1:length( files )
10 f = files(k).name;
11 fh = fopen( f , 'r');
12 total = 0;
13 while (~feof(fh))
14 s = fgetl( fh );
15 if ( any( regexp(s,'::') ) )
16 bits = regexp(s,'::', 'split')
17 m = str2num( bits{4} );
18 total = total + m;
19 else
20 continue
21 end
22 end
23 % store the result in matlab variable
24 % student_mark
25 % extract the name and initials - remove the rest of the gunk
26
27 %f2 = regexprep( f, '_[A-Z]?d+[A-Z]?_[a-zA-Z]d+_d+.mkd$','');
28 f2=regexprep( f, '_w{1,2}?d+w?_w{1}d+_d+.mkd$','')
29 % f2 may contain hyphenated names that are not valid Matlab variable
30 % names
31 ff2 = regexprep( f2, '-', '_Hyphen_');
32 result_str = [ ff2, '=', num2str( total )]
33 eval( result_str )
34 end
35
36 % Print a nice table of results
37 Data = who('S*');
38 for k = 1:length( Data )
39 fprintf( '%35s = %6.2fn', Data{k}, eval( Data{k} ) );
40 end
In Line 7, the dir function returns a structure with the
199. le name under consideration. We loop through the required
200. les in Lines 9 { 34. The regexp function in Line 15 returns a set of indices
where the pattern :: occurred in the string s. This pattern only picks up those
lines that contain the
201. eld separator ::. Then we split the line by this separator
(Line 16) which returns a cell bits containing the information we want. The
fourth
202. eld contains the mark for the question. Note that this still a string and
we need to convert to a number (Line 17). Having accumulated the marks, we
59
203. then store this result in a MATLAB variable extracted from the
204. le name. We
make sure that the variable does not contain any dashes - (Lines 28 - 31). Once
these variables are de
205. ned in the workspace, we extract the information (Lines
37 - 40) and format the information.
Example 22.8 UV Count. Counting pixels in an image! In forensic
study, images are obtained under UV light that capture forensic trace material.
These are collected by sticking circular patches onto test subjects. In this study,
it is required to count the number of lighted pixels. The colour image after some
cropping is shown in Fig. 13. This image is then converted to black and white
and is shown in Fig. 14.
Figure 13: An image taken under
UV.
Figure 14: An image taken under UV
after converting to black and white.
A typical row of black and white image consists of rows of zeros (black) and
1 (white). Our task is to count those 1's that are inside the circular patch.
One simple approach is to scan each row detecting the circular boundary on the
y. The diff function returns
206. rst order dierence of a vector x, ( xi+1 xi).
Using this vector d1 (Line 17), we
207. rst locate the lower edge of the circular
patch looking for the
208. rst occurrence of a -1 in the vector. Similarly, when we
leave the circular patch, we look for last occurrence of 1 in the vector. Now, we
count the lighted pixels between L and U in that row (Line 26). Note that this
algorithm needs further attention when there are lighted pixels on the perimeter
of the circular patch.
The complete program is shown below with some additional checks. In this
image there are 793177.
1 % Count lighted pixels in the circular disk
2
3 %% Load the file
4 %
5 A = imread('croppedF81DOT3.JPG');
6 level = 0.15;
7 bw = im2bw(A,level); % replaces pixels with luminence greater than level by 1
8 % this should produce pretty clean disk
60
209. 9 %
10 [r,c] = size(bw);
11 % process each row of data
12 % detect the circular boundary, L and U
13 % count the 1s betwen L U
14 uvCount = 0;
15 for k = 1:r,
16 row = bw(k,:);
17 d1 = diff(row);
18 if ( all(d1==0) )
19 % no circular boundary detected
20 count = 0;
21 else
22 L = min( find(d1==-1) ); % first occurrence of 1 - 0
23 U = max( find(d1==1) ); % last occurrence of 0 - 1
24 % we will miss the cout of the lighted
25 % pixel happens to be on the boundary
26 count = sum( row(L:U) );
27 uvCount = uvCount + count;
28 end
29 end
30
31 fprintf('uvCount: %dn', uvCount);
61
210. 23 Concluding Remarks
In this note only a subset of MATLAB commands are described to illustrate the
ease with which sophisticated numerical algorithms can be invoked at a fraction
of eort. MATLAB also provides a whole suite of functions/scripts to facilitate
computations in Signal Processing and Control Systems which are not discussed
here. For a list of available toolboxes on the system, type help. Some of these
toolboxes have limited number of licences and you need to check with your
tutor for further details. Also there are facilities to call your favourite algorithm
written in FORTRAN or C while you are within MATLAB 3. Finally, MATLAB generated
plots can be exported into your LATEX documents4.
3For further details see PRO-MATLAB, User's Guide, The MathWorks,Inc., 1989
4Save your plots in PNG format using the command print -dpng myfig.png. This will
create the required
211. le in your directory and is incorporated in your document in the normal
way.
62