an introduction to matlab with worked examples

68
MATLAB User’s Guide Dr. V. V. S. S. Sastry, Applied Mathematics and Scientific Computing, Centre for Simulation and Analytics, Cranfield University, Shrivenham, Swindon, Wiltshire SN6 8LA. email: v.v.s.s.sastry@cranfield.ac.uk 9 October 2014

Upload: eassessment-in-practice-symposium

Post on 28-May-2015

512 views

Category:

Education


4 download

DESCRIPTION

Basic introduction. Contains several worked examples to practice. Convenient index is provided to locate example code.

TRANSCRIPT

Page 1: An Introduction to MATLAB with Worked Examples

MATLAB User’s Guide

Dr. V. V. S. S. Sastry,Applied Mathematics and Scientific Computing,

Centre for Simulation and Analytics,Cranfield University,

Shrivenham, Swindon, Wiltshire SN6 8LA.email: [email protected]

9 October 2014

Page 2: An Introduction to MATLAB with Worked Examples

Contents

1 Getting Started 21.1 Help! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Basics 3

3 Matrix Operations 3

4 Point-wise Operations 4

5 Relational Operations 4

6 Defining Vectors 5

7 Addressing Matrix Elements 6

8 Referencing with 0-1 vectors 6

9 Pre-defined Matrices 7

10 Control Flow 810.1 for · · · end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810.2 while · · · end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910.3 if · · · else(if) · · · end . . . . . . . . . . . . . . . . . . . . . . . . . 910.4 switch ... case ...otherwise ... end . . . . . . . . . . . . . . . . . . 10

11 Using an Editor 10

12 Scripts and User Defined Functions 1112.1 Primary Functions and Sub-functions . . . . . . . . . . . . . . . 11

13 Numerical Computations 1313.1 Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . 15

14 Graphics 16

15 Handle Graphics 17

16 GUIs 24

17 Obtaining Hard Copy 30

18 MATLAB Quiz 31

19 MATLAB Tutorial Sheet 32

20 Model Answers for Tutorial Sheet 36

1

Page 3: An Introduction to MATLAB with Worked Examples

21 Common tasks in MATLAB 42

22 Worked Examples in Programming 52

23 Concluding Remarks 62

List of Figures

1 Plot of humps(x). . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Motion of Simple Pendulum. . . . . . . . . . . . . . . . . . . . . 163 quiver displays angle and magnitude of data. . . . . . . . . . . . . 174 Changing properties of a graphic object. . . . . . . . . . . . . . . 195 Creating simple inset plots. . . . . . . . . . . . . . . . . . . . . . 206 The user can select the lower left and top right corners of a box,

and display that portion in another part of the window. . . . . . 217 patch(X,Y,’c’) creates a filled polygon whose vertices are given

in X and Y using the colour ’c’. EdgeColor is used to highlightthe patch. Note the fill area for negative values of y. . . . . . . . 22

8 Greek letters, subscripts, etc. in graph annotation. The defaultinterpreter is TeX. . . . . . . . . . . . . . . . . . . . . . . . . . . 23

9 A simple pushbutton. When pressed displays ’Hello’ in the com-mand window, and reconfigures itself as a quit button. . . . . . . 25

10 Colour sampler. Adjust the values the Red, Green and Bluecomponent using the sliders. A sample of the colour is shown asa patch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

11 Playing with buttons. Demonstrates the use of embedding theCallBacks within the same function. . . . . . . . . . . . . . . . . 30

12 Triangular hat function . . . . . . . . . . . . . . . . . . . . . . . . 3313 An image taken under UV. . . . . . . . . . . . . . . . . . . . . . 6014 An image taken under UV after converting to black and white. . 60

2

Page 4: An Introduction to MATLAB with Worked Examples

Abstract

MATLAB is an interactive package to perform matrix based computations. Thepackage also contains several built-in functions to perform routine computationsin Numerical Analysis, Signal Processing, Control Systems and wide variety ofspecial functions in Applied Mathematics. Many specialist toolboxes are beingcontinually 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 toprovide the elementary principles of customizing the plots.

A new section on developing GUIs is included. One must exercise enormouscaution in developing GUIs in matlab as the code can get enormously large veryquickly.

In this guide, only a subset of MATLAB functions dealing with Matrix Algebraand Numerical Analysis are described in some detail. Further details on theseand other functions in the above mentioned areas can be found in [MATLABHigh-Performance Numeric Computation and Visualization Software, User’sGuide, The Math Works Inc., 1993 and Signal Processing Tool Box, by J.N.Little and L.Shure, The Math Works Inc., 1988].

Page 5: An Introduction to MATLAB with Worked Examples

Revision History

This User Guide has started its life around 1992. First version is made availablefor general use through the Compute Center in 1993. Since then the User Guidehas under gone several changes taking into account some of the mistakes, errorsand typos suggested by students, colleagues and well wishers. Thank you all foryour input. With this version I have decided to include this section as a way ofkeeping 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.

Modified eye(A), etc. They no longer work in V5.217 September 1999 Correction to the output of A < 0 in the Table. Shows three rows

now to be consistent with the definition of A above.3 November 2006 Changed the address block.1 November 2012 Changes to functions calling functions.9 October 2014 re-captured all figures; quad replaced by integral; changes to pa-

rameter passing to functions; included an index for easy reference

1

Page 6: An Introduction to MATLAB with Worked Examples

1 Getting Started

MATLAB is an interactive software package for scientific and engineering compu-tation. MATLAB is an abbreviation for MATrix LABoratory and was originallywritten (in the early 70s) to provide easy access to matrix software developedby the LINPACK and EISPACK projects. Since then it has embraced virtuallyevery branch of numerical mathematics.

Matlab can be started on Unix/Linux by typing the command matlab atunix prompt or from the Start button on Windows platform.

The programs and code snippets are developed using MATLAB Version8.3.0.532 (R2014a). The MATLAB commands can be issued at the double angledprompt >>.

Now you can issue any MATLAB command. If you are a first time user, youare urged to go through the demonstration programs which illustrate its variouscapabilities. 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 canalso be accessed via the web browser using doc.

2

Page 7: An Introduction to MATLAB with Worked Examples

2 Basics

Matrices are defined as a list enclosed by square brackets, where the rows areseparated by ”;” and the elements are separated by a blank or a comma. Forexample,

A = [1 2 3; 4 5 6 ; 7 8 9]

Matrix elements can be defined using any valid MATLAB expression. Here, pi andi are predefined MATLAB constants. For example,

x = [ exp(i*pi/2), sqrt(2), cos(pi/4) ];

defines a row vector x = [i√2 cos(π/4)]. Individual entries of a matrix are

referenced with indices enclosed by parentheses, ( and ). Thus, x(2) correspondsto the second element of the vector in the above example. By defining 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 defined from smaller matrices.For example,

r = [10 11 12];A = [A;r];

would result in1 2 34 5 67 8 910 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 standardmathematical notation. For example, to add the matrices A and B and thenmultiply 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

Page 8: An Introduction to MATLAB with Worked Examples

Matrix operation MATLAB syntaxaddition and multiplication (A+ B) ∗ Ctranspose of A A′

inverse of A inv(A)Matrix divisionTo solve A ∗ X = B A\ BTo solve X ∗ A = B B/Apower 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 asdefined above.

Z = evaluates to remarksx. ∗ y [4 10 18] [1× 4 2× 5 3× 6]

x.\y [4 2.5 2] [ 41 ,52 ,

63 ]

x./y [0.25 0.4 0.5] [ 14 ,25 ,

36 ]

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 suchan operation is a 0-1 matrix of same dimension. find is a helpful command whichreturns the index; and can be used in conjunction with relational operators. Forexample,

x = [1 2 3 4 5 6 7 8 9 5];i = find(x>3.0)

4

Page 9: An Introduction to MATLAB with Worked Examples

would return

[4 5 6 7 8 9 10]

for i. Now using

x(i) = 10*ones(i);

modifies the elements x(4),x(5),x(6) etc. Here the command ones(i) generatesa matrix of dimension i whose elements are all 1. As a result the the vector xcontains

[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 thecommand i = find( a == max(a) )?

6 Defining 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 isto be understood as a means of separating the lower limit and upper limit ofthe sequence. A default step size of 1 is understood. A required step size canbe defined 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 specified),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

Page 10: An Introduction to MATLAB with Worked Examples

7 Addressing Matrix Elements

Individual matrix elements can be referenced using subscript notation. For thematrix

A =

1 2 3 −14 5 6 −27 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 −14 5 6 −2

7 15 9 −3

A subscript can also be a vector. Thus specifying A(1 : 2, 3) yields first two

rows of the third column, i.e, [3 6]. A colon, ’:’ can be used as a wild card torefer to all the elements in a column or a row. Thus A(:, 2) refers to all theelements in the 2nd column. The following table summarises the effects of someuseful commands.

command resultA(2, :) [4 5 6 − 2]

A(2 : 3, 2 : 4)

(5 6 −2

15 9 −3

)A(:, :) is the same as AA(:) matrix A arranged as a single columnmax(A) row containing maximum element of columns of

A, i.e., [7 15 9 − 1]max(max(A)) 15find(A == max(max(A))) 6 ,returns linear index where the matrix is treated

as a single column.

A < 0

0 0 0 10 0 0 10 0 0 1

8 Referencing with 0-1 vectors

The 0-1 vectors are usually created from relational operations, which can beused to reference submatrices. For example,

x = [1 2 3 4 5 10 12 15 16]

Then the following commands

6

Page 11: An Introduction to MATLAB with Worked Examples

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 commandx = x( (x >= 4) & (x < 12) )?

9 Pre-defined Matrices

Several well known matrices have already been defined for quick reference andfor your own use; and some of these matrices are listed below.

MATLAB syntax purposehadamard(k) returns the Hadamard matrix of order n = 2k

hankel(c) Hankel matrixhankel(c,r) See Manual or use Helphilb(n) Hilbert matrix of dimension ninvhilb(n) inverse of Hilbert matrixmagic(n) magic square of order n

There are some useful matrices which are mostly used in point-wise operationsand these are illustrated below which are self-explanatory.

7

Page 12: An Introduction to MATLAB with Worked Examples

matrix output

ones(3)

1 1 11 1 11 1 1

Z = zeros(3,4)

0 0 0 00 0 0 00 0 0 0

ones(Z)

1 1 1 11 1 1 11 1 1 1

eye(4)

1 0 0 00 1 0 00 0 1 00 0 0 1

eye(Z)

1 0 0 00 1 0 00 0 1 0

rand(3)

0.2190 0.6793 0.51940.0470 0.9347 0.83100.6789 0.3835 0.0346

rand(Z)

0.0535 0.0077 0.4175 0.93040.5297 0.3834 0.6868 0.84620.6711 0.0668 0.5890 0.5269

10 Control Flow

MATLAB provides two commands for repeated execution of a group of commandsand these are illustrated with examples.

10.1 for · · · endA group of statements are executed a fixed number of times with the help of for· · · end construct. For example,

for j=1:5,x(j) = 0,end

assigns 0 to the fist five elements of x. Loops can be nested. Remember thateach for must have a corresponding end. To define a 3× 3 Hilbert’s matrix, onecould use the following statements.

for i=1:3for j=1:3

a(i,j) = 1/(i+j-1);end

end

8

Page 13: An Introduction to MATLAB with Worked Examples

for loops can go backwards as well. To define the Vandermonde matrixxn−11 · · · x2

1 x1 1xn−12 · · · x2

2 x2 1... · · ·

...xn−1n · · · 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 · · · endTo 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 first integer n for which n! is a 100 digit number. eps in MATLAB

is defined as follows.

small = 1;while (1+small ~= 1)

small = small/2;endsmall = small*2

Try the above lines on the computer you are using to find eps.

10.3 if · · · else(if) · · · endFinally, MATLAB provides if · · ·else(if) · · · end construct for conditional branching.For example, to define a 5× 5 matrix A such that

aij = 2 ,i = j= -1 ,|i− j| = 1

one can issue the following commands.

for i=1:5,for j=1:5,

if i==j,

9

Page 14: An Introduction to MATLAB with Worked Examples

a(i,j) = 2;elseif abs(i-j) == 1,a(i,j) = -1;

elsea(i,j) = 0;

endend

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 ,endendeps = eps*2

10.4 switch ... case ...otherwise ... end

switch block enables conditional execution. In its simplest form, switch executesthe first case where switch expr == case expr. The following example illustratesthe usage.

Example 10.1 Evaluate linear or quadratic or cubic function depending on theuser 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 writingefficient code. Pay attention to those orange scrolls on the right hand side.

10

Page 15: An Introduction to MATLAB with Worked Examples

12 Scripts and User Defined Functions

A script file (or just script) is a file containing a sequence of MATLAB commands,which can be invoked at MATLAB prompt level. These files must have extension’.m’ and reside in MATLAB sub-directory of your area. The following is an exampleof a script to generate the first 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 file called, fib.m in adirectory, ~username/matlab. Then the above lines are invoked by simplytyping in the name of the file, in this case fib at the MATLAB prompt.

In contrast a function file will allow arguments to be passed to the scriptfile. Thus to define a window or hat function of half-width a,

y = 1, |x| ≤ 1

= 0, otherwise

one can define the following M-file.

function y = hat(x,a),y = ( abs(x) <= a );

12.1 Primary Functions and Sub-functions

With MATLAB Version 5, M-files can contain more than one function. The firstfunction 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 variablesdefined in the primary function are not available inside any of the subfunctionsunless declared global.

Example 12.1 Compute arithmetic, geometric and harmonic mean of a list ofnumbers.

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

Page 16: An Introduction to MATLAB with Worked Examples

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

Page 17: An Introduction to MATLAB with Worked Examples

Note that the variable n defined in the primary function need to be passedexplicitly as an argument to subfunctions.

13 Numerical Computations

Besides matrix computations, MATLAB provides several commands or scripts toperform routine numerical computations such as numerical integration, differen-tiation, approximate solutions of nonlinear equations, optimization and numer-ical solution of differential equations. There are extensive facilities to displayboth one dimensional and two dimensional plots and provides a very simplemechanism to obtain hard copies of your precious plots. Some of these func-tions are illustrated below. Define the function

y(x) =1

(x− 0.3)2 + 0.01+

1

(x− 0.9)2 + 0.04− 6.0

in an M-file 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 thecommands

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 thelocation 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

Page 18: An Introduction to MATLAB with Worked Examples

−1 −0.5 0 0.5 1 1.5 2−20

0

20

40

60

80

100Plot of humps(x)

x

y =

hum

ps(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 zerosin the neighbourhoods of x = 0 and x = 1. These zeros are obtained using thecommands

zero1 = fzero( @humps, 0 )zero1 =-0.1316zero2 = fzero( @humps, 1 )zero2 =1.2995

13.1 Differential Equations

Numerical approximations for the solutions of differential equations are com-puted using either ode23 or ode45. Both of the routines use automatic step size

14

Page 19: An Introduction to MATLAB with Worked Examples

Runge-Kutta-Fehlberg integration methods. ode23 uses a simple 2nd and 3rdorder pair of formulae for medium accuracy, while ode45 uses 4th and 5th orderformulae for higher accuracy.1 For example, consider the second order nonlineardifferential equation

y + 0.3 y +g

lsin y = 0

with the initial conditions

y(0) = α

y(0) = 0

First one must express the above differential equation as a system of two firstorder equations which is achieved by setting y1 = y2 and y2 = y. Thus, weobtain

y1 = −0.3y1 −g

lsin y2

y2 = y1

and the initial conditions transform to

y1(0) = 0

y2(0) = α

Next the pair of first order equations are stored in an M-file, say, shm.m whichis required to invoke ode23. For illustration purposes choose g = 9.8 ms−2 andl = 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 tosimulate the motion of the pendulum for the first 20 seconds, issue the followingcommands.

t0 = 0;tfinal = 20;tspan = [t0 tfinal];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 Methodsfor Mathematical Computations, Prentice Hall, 1977.

15

Page 20: An Introduction to MATLAB with Worked Examples

Displacement

Angular velocity

0 2 4 6 8 10 12 14 16 18 20−0.8

−0.6

−0.4

−0.2

0

0.2

0.4

0.6

0.8

t

Dis

plac

emen

t and

Ang

ular

vel

ocity

Figure 2: Motion of Simple Pendulum.

14 Graphics

Apart from the straight forward x-y plots, MATLAB provides a wide range ofplot styles, which can be found in MATLAB Quick Reference. For an interestingcollection 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 todisplay the plot. We wish to generate the surface z = x exp(−x2 − y2) over thedomain x ∈ [−2, 2] and y ∈ [−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

Page 21: An Introduction to MATLAB with Worked Examples

[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.

−2

0

2

−2

−3

0

3−0.5

0

0.5

Surface plot of z = x * exp( −x^2 − y^2)

5 10 15 20

5

10

15

20

25

30

Quiver Plot

Figure 3: quiver displays angle and magnitude of data.

15 Handle Graphics

Each and every graphics object has a unique identifier and is usually referredto as a handle, and hence the name HandleGraphics. Current properties of thegraphic object are queried with get command while the properties are definedusing 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

Page 22: An Introduction to MATLAB with Worked Examples

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

Page 23: An Introduction to MATLAB with Worked Examples

−2 −1.5 −1 −0.5 0 0.5 1 1.5 20

0.5

1

1.5

2

2.5

3

3.5

4

Figure 4: Changing properties of a graphic object.

Example 15.1 Inset. A portion of the original plot is displayed in the samedrawing 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

Page 24: An Introduction to MATLAB with Worked Examples

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

−0.5 0 0.5−0.3

−0.2

−0.1

0

0.1

0.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

Page 25: An Introduction to MATLAB with Worked Examples

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2−0.4

−0.2

0

0.2

0.4

0.6

0.8

0.1 0.2 0.3 0.4 0.5−0.2

−0.1

0

0.1

0.2

Figure 6: The user can select the lower left and top right corners of a box, anddisplay that portion in another part of the window.

Example 15.3 Area under curve. To fill 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

Page 26: An Introduction to MATLAB with Worked Examples

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2−20

0

20

40

60

80

100

Figure 7: patch(X,Y,’c’) creates a filled polygon whose vertices are given inX and Y using the colour ’c’. EdgeColor is used to highlight the patch. Notethe fill 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 wouldbe 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

Page 27: An Introduction to MATLAB with Worked Examples

J ν + 1/2 (x) for ν = 0,1,2

J ν

+ 1

/2

(x)

0 1 2 3 4 5 6 7 8 9 10−0.4

−0.2

0

0.2

0.4

0.6

0.8

x

Figure 8: Greek letters, subscripts, etc. in graph annotation. The defaultinterpreter 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 interfaceobjects - 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 define a CallBack for the user interface object.

Example 16.1 A simple example. Define a pushbutton which prints hello tothe screen.

% a simple pushbutton which says "hello"

%

pb = uicontrol(’Style’,’pushbutton’, ...

’Position’,[30, 30, 72, 36], ...

’String’,’PushMe’, ...

23

Page 28: An Introduction to MATLAB with Worked Examples

Figure 9: A simple pushbutton. When pressed displays ’Hello’ in the commandwindow, and reconfigures itself as a quit button.

’CallBack’,’disp(’’Hello ...’’)’ );

Note that the bottom left corner of the UI object (i.e., pushbutton is placedin the Figure window at (30,40). Default units are pixels and the origin is atthe bottom left corner of the Figure window. Next we define two additionalproperties of pushbutton – the text that appears on the button (PushMe), andwhat to do when the user presses the button (CallBack). Usually the CallBackstring is a matlab script.

Example 16.2 A pushbutton which reconfigures itself as a Quit button.

pb = uicontrol(’Style’,’pushbutton’, ...

’Position’,[30, 30, 72, 36], ...

’String’,’PushMe’, ...

’CallBack’,[...

’disp(’’Hello ...’’);’, ...

’set(pb,’’String’’,’’Quit’’);’, ...

’set(pb,’’CallBack’’,’’delete(gcf)’’)’] );

24

Page 29: An Introduction to MATLAB with Worked Examples

The CallBack string here is bit more involved. Recall that strings can beconveniently constructed in Matlab as an array, enclosed within square brackets.When using continuation marks, you must keep one quoted string per line. Inother words, don’t continue a quoted string. If your CallBack string is moreinvolved 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 collectingdata from other UI components to achieve a desired computation. Three slidersare used to represent Red, Green and Blue components of the required colour. Asample patch is shown in the figure.

% 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

Page 30: An Introduction to MATLAB with Worked Examples

%

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

Page 31: An Introduction to MATLAB with Worked Examples

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

Page 32: An Introduction to MATLAB with Worked Examples

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. Define a function which handlesall major events. The function is normally with one argument, say, action.Branch to appropriate segment depending on the action. The following codeillustrates 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

Page 33: An Introduction to MATLAB with Worked Examples

% 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

Page 34: An Introduction to MATLAB with Worked Examples

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 file output in your sub-directory. This facility can be turned off by issuing diary off or simply diary.The diary toggles between on, off values.

Graphical output can be redirected to a suitable plotter or laser printer.Having generated the required plot, type print at the MATLAB prompt. Theoutput goes to the default printer. For saving the plot in various graphics fileformats, type help print.

30

Page 35: An Introduction to MATLAB with Worked Examples

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 — A\B 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 defined 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 isreturned by such a statement?

17. Typing pi at MATLAB prompt displays the number, 3.1416. What is thecommand to display the available decimals?

18. Can you call programs written in FORTRAN or C?

31

Page 36: An Introduction to MATLAB with Worked Examples

19 MATLAB Tutorial Sheet

1. Basic Commands

(a) Define the vector x = (−3,−4, 2, 1, 0, 2, 3, 5, 10) (Remember to usematlab 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) Define the matrixA =

1 0 6 −3

−1 2 0 20 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 = find( A == max( max(A) ) )

vii. P = poly(A) and roots(P) .

(c) Given A =

1 2 34 5 67 8 0

and b =

135

, 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 −i0 1 11 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

Page 37: An Introduction to MATLAB with Worked Examples

y = 1− xy = 1 + x

-2 -1 0 1 2 x

1

y6

-

Figure 12: Triangular hat function

(a) to extract the indicated (elements are shown in boldface) submatrix

of A =

1 2 34 5 67 8 9

.

(b) to find the maximum element of A.

(c) to find the location of the maximum element of A.

(d) to define a 4× 4 matrix B so that

bij = 2 i = j= -1 |i− j| = 1= 0 otherwise

(e) to find the determinant of B. If Bn denotes an n × n matrix, is ittrue that det(Bn) = n+ 1 ?

(f) to find the eigenvalues and eigenvectors of B.

(g) to define the function

y =1

(x2 − 1)+ 2

(h) to plot the function defined in 4(g).

(i) to find the zeros of the function defined in 4(g).

(j) to find the roots of the polynomial

s3 − 6s2 − 72 s− 27

5. Define the MATLAB function as described in Fig. 12 in a file called triang.m.Check your function definition by plotting it.

33

Page 38: An Introduction to MATLAB with Worked Examples

6. Case Study — Nonlinear PendulumThe equation of motion of a strongly damped simple pendulum is givenby

θ + 0.3 θ + sin θ = 0

Subject to the initial conditions

θ(0) =π

4

θ(0) = 0

simulate the motion of the pendulum for the first 15 seconds. Experimentusing ode23 and ode45 and plot your results. The quantity

δ = lnx1

x2

where x1 and x2 are any two successive amplitudes is called logarithmicdecrement. With the help of the plot you have generated and using ginputcommand estimate the logarithmic decrement.[Hint: Use the help facility for the syntax of relevant commands. The abovesecond order differential equation can be expressed as a system of two firstorder differential equations as shown below.

x1 = −0.3 x1 − sinx2

x2 = x1

]

7. Case Study — Population Growth2

Let Fi and Ci denote number of foxes and chicken at a time step i. Atthe 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 theinitial population as F1 = 100 and C1 = 1000, the above equations can beused 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 =

(1001000

).

2With due acknowledgements to Ben Noble and James W Daniel, Applied Linear Algebra,Prentice-Hall, 1988, ISBN: 0-13-593609-8.

34

Page 39: An Introduction to MATLAB with Worked Examples

Hence,

x2 = Ax1

x3 = Ax2

= AAx1

= A2x1 etc.

In generalxi+1 = Aixi for i = 0, 1, · · ·

(a) For a low kill rate of k = 0.1 find the two populations. Plot theresults. Do the populations reach an equilibrium?

(b) For a high kill rate of k = 0.18 find the two populations. Plot theresults. Do the populations reach an equilibrium?

(c) For an intermediate kill rate of k = 0.16 find 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 theeigenvalues of the matrix.

Find the eigenvalues for the above three cases. Can you suggest a conditionunder which Ai goes to 0 as i → ∞.

35

Page 40: An Introduction to MATLAB with Worked Examples

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 = (x<3) returns the vector

1 1 1 1 1 1 0 0 0 1 1 1

C. L = (x<4 & 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

Page 41: An Introduction to MATLAB with Worked Examples

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 eachcolumn.max( max(a) ) returns the scalar 6 which is the maximum element inthe matrix.

vi. returns the location of the maximum element treating the matrix asa single column. You have to do extra work to express that numberon matrix ’i,j’ notation.

vii. poly(a) returns the coefficients of the characteristic polynomial of ma-trix a. The coefficients 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

Page 42: An Introduction to MATLAB with Worked Examples

(c) Remember to use the column vector for b. Use x = a\b which returns thecolumn 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 matrixof zeros of size a respectively.

4. Remember to clear the matrix a.

(a) to extract the submatrix consisting of rows two through three and columnstwo 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 defined as

function a = bandm(n,dentry,sup,sub),

for i=1:n,

for j = 1:n,

38

Page 43: An Introduction to MATLAB with Worked Examples

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 file 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 precedingspace! 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 coefficients are entered start-ing with that of the highest degree. If a particular coefficient is absent,remember to enter zero.

5. This requires patience and thorough understanding of MATLAB syntax. Thefollowing scripts do the job:

39

Page 44: An Introduction to MATLAB with Worked Examples

(a) This uses logical indexing.

function y = triang(x)

xl0 = x( x<-1 );

xr0 = x( x>1 );

xl = x( x>=-1 & x<0 );

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=(-1<x).*(x<0).*(x+1)+(0<=x).*(x<1).*(1-x);

end

(c) and yet another compact definition below:

function y = triang3( x ),

y = max( min( (x+1), (1-x) ), 0 );

6. First define the system of first 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 file 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 first twopeaks.

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

Page 45: An Introduction to MATLAB with Worked Examples

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:

90± 10√9− 50 k

100(1)

41

Page 46: An Introduction to MATLAB with Worked Examples

21 Common tasks in MATLAB

This section lists a number of examples describing how you can put matlab tobest use for solving typical problems one encounters.

Example 21.1 Generate a fixed 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 resultin 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 numbersin an interval.

rand function generates the required numbers in the interval. Map these numbersto 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],

first 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 measuresare very important – how much time does my code take and how many floatingpoint operations does it require.

Computation of the above two measures are illustrated for matrix multipli-cation using the code below:

42

Page 47: An Introduction to MATLAB with Worked Examples

% 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.00044863650 9.28326e-05

100 0.000293572500 0.01347311000 0.0998544

Matrix multiplication counts 2N3 flops for an N ×N matrix. So watch outbefore you run this script for very large matrices! sprintf is convenient to formatitems, and to accumulate statistics I need to convert them to a matrix of stringsas each string may be of different size. Note also that these measurements canvary from run to run and should be treated with caution.

More reliable timing measurements can be obtained using timeit functionavailable 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

Page 48: An Introduction to MATLAB with Worked Examples

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 whereyou are interested in determining the root of a continuous function. This func-tion involves a parameter, and you are interested finding the root for variousvalues 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

Page 49: An Introduction to MATLAB with Worked Examples

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+1x

k

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 aboutscalar or vector arguments.

45

Page 50: An Introduction to MATLAB with Worked Examples

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 log(1+x)

% vectorized version - x is a row

function y = vseries(x),

tsum = x; % vector

term = x; % vector

k = 1;

while( norm(tsum+term) ~= norm(tsum) )

% you need norm here

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 |xn+1 − xn| ≤ 0.0005.

Let us write the function which accepts two input arguments – an initialguess 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 vectorconsisting of intermediate iterates. This is handy if you want to plot them. Hereis the code.

46

Page 51: An Introduction to MATLAB with Worked Examples

% 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

Page 52: An Introduction to MATLAB with Worked Examples

starting with an initial guess x = [3,−1]′.

We are going to use function fsolve from Optimization Toolbox. First, definethe system of non-linear equations in a function file 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. Thisparticular example can be converted into a higher order polynomial. Usingsecond of the equations 8, namely y = 1/x in the first, we immediately obtainx4 − 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-defined functions. Quiteoften we need to work with function inputs to function. A typical example isimplementing Newton-Raphson’s method in matlab. One normally defines thefunction and derivative in two separate function files. How do you capture theirvalues at a specific 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 criteriais by no means sophisticated.

48

Page 53: An Introduction to MATLAB with Worked Examples

% 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, define thefunction and its derivative in a function file 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

Page 54: An Introduction to MATLAB with Worked Examples

its =

Columns 1 through 4

0.10000000000000 0.52252289377317 0.56677815778619 0.56714326628276

Column 5

0.56714329040978

You can confirm this result by running nr with different 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 define 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

Page 55: An Introduction to MATLAB with Worked Examples

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 anysignificant approximation unless you use quadruple or higher precision!

51

Page 56: An Introduction to MATLAB with Worked Examples

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 exceeding10?

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: %.3f\n’, tot)

15 fprintf(’Required rands: %5d\n’, 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 ofa 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, basedon readings that are greater than the average of those around them. One suchneighbourhood is defined as 4-neighbourhood takes the average of elements in N,S, E and W of each element of the array of measurements. For simplicity, wecompute these averages starting at element (2,2) and stopping one short of thelast column and last row.

Your task is to produce a matrix M of same size as that of A that contains1 where the value exceeds the average of elements in 4-neighbourhood.

A =

21 21 22 30 40 21 34 4521 22 23 30 45 21 37 4022 23 24 45 46 47 38 3922 23 24 35 46 47 38 3823 24 25 36 46 49 37 3623 24 25 37 39 48 36 3523 24 25 25 26 25 26 2523 25 26 27 28 29 30 31

52

Page 57: An Introduction to MATLAB with Worked Examples

We loop through the rows and columns with the help of two loops. Everytime we visit an element, we access the elements of 4-neighbourhood and see ifthe current element is a relative maximum (Lines 21 - 26). The complete codeis 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

Page 58: An Introduction to MATLAB with Worked Examples

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 oddintegers, we chnage the summation index tot n. As k = 1, 2, 3, · · ·, n runs through 1, 3, 5, · · ·. Two approaches are shownbelow - one using straight forward for loop, and another using array operations.The time info will differ 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 1\n’);

16 fprintf(’ Number of terms, N: %d\n’, N);

17 fprintf(’ an approximation to pi: %.12f\n’, pi_approx);

18 fprintf(’ abs. error (pi - pi_approx): %.12f\n’, abs(pi-pi_approx));

19 fprintf(’ elapsed time: %.6f\n’, 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 2\n’);

31 fprintf(’ Number of terms, N: %d\n’, N);

54

Page 59: An Introduction to MATLAB with Worked Examples

32 fprintf(’ an approximation to pi: %.12f\n’, pi_approx2);

33 fprintf(’ abs. error (pi - pi_approx): %.12f\n’, abs(pi-pi_approx2));

34 fprintf(’ elapsed time: %.6f\n’, 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 integeras R = ceil(100*rand(1). Your task is to guess the number which can beentered 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 howmany attempts the user may take. When using this type of while loop, domake 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

Page 60: An Introduction to MATLAB with Worked Examples

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 ofmonthly averages of temperature since 1659 to July, 2014. The data set can beobtained 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, andreturns the year(s), and month(s) for which the inequality is satisfied. Exampleusage:

56

Page 61: An Introduction to MATLAB with Worked Examples

>>[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 stringcondStr with the appropriate find command.

Example 22.6 Write a program that counts the number of elements that arein 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 basiccounting is done through counting the one’s generated by the logical A>L &

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( A>L & 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 studentsare stored in a file of the form:

57

Page 62: An Introduction to MATLAB with Worked Examples

# 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 field is the student’s response while third field represents thecorrect response to the question. The final filed is the mark awarded to thequestion.

These marked files are stored in a directory with the extension .mkd.The marked files 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 files 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

Page 63: An Introduction to MATLAB with Worked Examples

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.2f\n’, Data{k}, eval( Data{k} ) );

40 end

In Line 7, the dir function returns a structure with the field name .name

that refers to the file name under consideration. We loop through the requiredfiles in Lines 9 – 34. The regexp function in Line 15 returns a set of indiceswhere the pattern :: occurred in the string s. This pattern only picks up thoselines that contain the field separator ::. Then we split the line by this separator(Line 16) which returns a cell bits containing the information we want. Thefourth field contains the mark for the question. Note that this still a string andwe need to convert to a number (Line 17). Having accumulated the marks, we

59

Page 64: An Introduction to MATLAB with Worked Examples

then store this result in a MATLAB variable extracted from the file name. Wemake sure that the variable does not contain any dashes - (Lines 28 - 31). Oncethese variables are defined in the workspace, we extract the information (Lines37 - 40) and format the information.

Example 22.8 UV Count. Counting pixels in an image! In forensicstudy, 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 somecropping is shown in Fig. 13. This image is then converted to black and whiteand is shown in Fig. 14.

Figure 13: An image taken underUV.

Figure 14: An image taken under UVafter converting to black and white.

A typical row of black and white image consists of rows of zeros (black) and1 (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 thefly. The diff function returns first order difference of a vector x, ( xi+1 − xi).Using this vector d1 (Line 17), we first locate the lower edge of the circularpatch looking for the first occurrence of a -1 in the vector. Similarly, when weleave the circular patch, we look for last occurrence of 1 in the vector. Now, wecount the lighted pixels between L and U in that row (Line 26). Note that thisalgorithm needs further attention when there are lighted pixels on the perimeterof the circular patch.

The complete program is shown below with some additional checks. In thisimage 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

Page 65: An Introduction to MATLAB with Worked Examples

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: %d\n’, uvCount);

61

Page 66: An Introduction to MATLAB with Worked Examples

23 Concluding Remarks

In this note only a subset of MATLAB commands are described to illustrate theease with which sophisticated numerical algorithms can be invoked at a fractionof effort. MATLAB also provides a whole suite of functions/scripts to facilitatecomputations in Signal Processing and Control Systems which are not discussedhere. For a list of available toolboxes on the system, type help. Some of thesetoolboxes have limited number of licences and you need to check with yourtutor for further details. Also there are facilities to call your favourite algorithmwritten in FORTRAN or C while you are within MATLAB 3. Finally, MATLAB generatedplots can be exported into your LATEX documents4.

3For further details see PRO-MATLAB, User’s Guide, The MathWorks,Inc., 19894Save your plots in PNG format using the command print -dpng myfig.png. This will

create the required file in your directory and is incorporated in your document in the normalway.

62

Page 67: An Introduction to MATLAB with Worked Examples

Index

πapproximation, 54

==, 5logical equal, 4

LATEXin graph annotation, 230-1 indexing, 64-neighbourhood, 52

abs, 11all, 60array sections, 3

bincounts.m, 57boolean indexing, 6

callback, 24nested, 28

ceil, 55colon,:

operator, 5contour, 16curvefill ex1.m, 22customizing plots, 17

diff, 60dir

with filtered input, 58drum.m, 44

editor, 10eigenvalues, 35entering

array, 3eval, 56

feof, 58feval, 48fib.m, 11find, 4fminunc, 13fopen, 58for loop, 8fprintf, 52fsolve, 47

functionexample, 11primary, 11sub-function, 11user defined, 11

fzero, 14

get, 17getMarks1.m, 57getYearMonth.m, 56ginput, 21, 34global, 44gradient, 16grid, 13guess1.m, 55guessing game, 55

hat, 11how many rands 1.m, 52humps.m, 13

if block, 9im2bw, 60imread, 60input, 55inset ex1.m, 19inset ex2.m, 21integral, 13invoking

script, 11iterations, 46iters.m, 46

length, 58linspace, 5local maxima, 52

matrix as a column, 6matrix multiplication, 3max, 5mesh, 16meshgrid, 16

negation

63

Page 68: An Introduction to MATLAB with Worked Examples

~, 4Newton-Raphson method, 48non-linear equations

solutions, 47norm, 45nr.m, 48nrex1.m, 48nrex1d.m, 48

ode23ode45, 15

ones, 5

p2.m, 60patch, 22pb1.m, 24pi, 3plot, 13

inset, 19with shaded patch, 22

point-wise operations, 4prod, 9push button

uicontrol, 24

quiver, 16

rand, 52, 55, 57regexp, 58

split, 58regexprep, 58relmax1.m, 52roots, 48

sandq.m, 16script, 11sdrum2.m, 44series summation

scalar argument, 45vector arguments, 45

series pi 1.m, 54set, 17shm.m, 15, 40sprintf, 43sseries.m, 45str2num, 43, 58string processing, 56

subplot, 16sum, 57summation of series, 54switch block, 10sys.m, 47

t4g.m, 39tic, 54timeit, 43tmult.m, 42tmult2.m, 43toc, 54triang.m, 33

UV count, 60

vseries.m, 45

weather.dat, 56while, 11, 45, 52

indefinite loop, 55while loop, 9who, 58

xcolsamp.m, 24xgui2.m, 28xint1.m, 50xint2.m, 50

64