matlab

37
Matlab Basics Christian Roessler U Melbourne June 2004 1 Elementary Syntax and Predened Tasks 1.1 Declaring Variables, Vectors, and Matrices A constant, vector, or matrix is declared using the syntax "name = value "- for example, >> a=3; >> some_number=0; creates two constants "a" and "some_number" with assigned values 3 and 0. If the value is a string, it is placed in single quotation marks: >> outcome=Hypothesis rejected.; If the value is a vector or matrix, it is placed in square brackets, and the entries are spaced by blanks (or commas): >> some_vector=[0 1 2 3]; creates a row vector with four elements. To divide into columns, enter the rows separated by semicolons: >> column_vector=[0;1;2;3]; creates a column vector with four elements, and >> some_matrix=[0 1;2 3]; creates a square matrix with the same elements. It is possible to create a matrix from existing matrices and vectors. For example, 1

Upload: imadakhdar

Post on 12-Nov-2014

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: matlab

Matlab Basics

Christian RoesslerU Melbourne

June 2004

1 Elementary Syntax and Prede�ned Tasks

1.1 Declaring Variables, Vectors, and Matrices

A constant, vector, or matrix is declared using the syntax "name = value" -for example,

>> a=3;

>> some_number=0;

creates two constants "a" and "some_number" with assigned values 3and 0. If the value is a string, it is placed in single quotation marks:>> outcome=�Hypothesis rejected.�;If the value is a vector or matrix, it is placed in square brackets, and the

entries are spaced by blanks (or commas):

>> some_vector=[0 1 2 3];

creates a row vector with four elements. To divide into columns, enterthe rows separated by semicolons:

>> column_vector=[0;1;2;3];

creates a column vector with four elements, and

>> some_matrix=[0 1;2 3];

creates a square matrix with the same elements. It is possible to createa matrix from existing matrices and vectors. For example,

1

Page 2: matlab

>> column_vector=[1;2];

>> clone=[column vector;column vector];

creates a column vector of four elements.

>> concatenated=[some_matrix;column_vector]

ans =

0 2 1

1 3 2

results in a 2�3 matrix. Observe that, since some_matrix is 2�2, it canonly form a row with a vector or matrix that has two rows. It could not forma column with column_vector, since they do not have the same number ofcolumns. Concatenation of strings is accomplished by forming a row vector:>> afterthought=� Too bad!�;>> [outcome afterthought]ans =

Hypothesis rejected. Too bad!To transpose a vector or matrix, use the prime operator:

>> some_matrix�

ans =

0 2

1 3

To rede�ne some_matrix as the transpose, it must be declared again:

>> some_matrix=some_matrix�

some_matrix =

0 2

1 3

Often matrices of random numbers must be generated. To create anm�nmatrix of uniformly distributed random numbers between 0 and 1, use thesyntax "rand(m;n)" or alternatively "rand(m)" if m = n, so that the matrixis square.

>> random_matrix=rand(20);

>> random_vector=rand(1,20)�;

2

Page 3: matlab

creates a 20 � 20 square matrix and a column vector with twenty ele-ments that are randomly drawn from a uniform distribution on the interval[0; 1]. If a di¤erent distribution is required, one typically creates a uniformlydistributed matrix �rst and transforms it.Matlab displays some numbers in scienti�c notation. The expression

1:0e+ 003 represents 1:0 � 103 = 1000; etc. So

1.2577e+003

equals 1257:7. To indicate that an entire vector is to be scaled, Matlabshows the factor on a separate line before displaying the vector. The vector

1.0e+003 *

6.2568 9.0000 0.8850

has elements 6256:8, 9000, and 885. To get Matlab to display more digits,type "format long". From this point on, Matlab will always show sixteenplaces. To toggle back to six places, type "format short".

>> format long

ans =

1.41421356237310

>> format short

ans =

1.4142

1.2 Operators

Matlab interprets operators by default as matrix operators. Therefore, mul-tiplication of vectors and matrices requires conformability.

>> x=[2 7];

>> new_vector=x*some_matrix

>> new_vector =

7 25

Division is equivalent to multiplication by the inverse.

3

Page 4: matlab

>> inv(some_matrix)

ans =

1.5000 1.0000

0.5000 0.0000

>> some_matrix/some_matrix�

ans =

2.0000 0.0000

1.5000 0.5000

>> some_matrix*inv(some_matrix�)

ans =

2.0000 0.0000

1.5000 0.5000

Raising a matrix to a power is interpreted as multiplication by the samematrix.

>> some_matrix^2

ans =

2.0000 3.0000

6.0000 11.0000

>> some_matrix*some_matrix

ans =

2.0000 3.0000

6.0000 11.0000

To perform an array operation (element by element) on two same-dimensionalobjects, place a dot in front of the operator:

>> new_vector.*x

ans =

14 175

>> new_vector./x

ans =

0.2857 0.2800

4

Page 5: matlab

>> new_vector.^2

ans =

49 625

Matrix addition and subtraction are identical to array addition and sub-traction. We have already seen the syntax for matrix inversion "inv(matrix)"- the determinant of a matrix is calculated by "det(matrix)", and the rankby "rank(matrix)".

1.3 Plotting a Function

The �rst step towards plotting a function is to select a set of point in thedomain on which the function is going to be evaluated. This is called thegrid. If the function is discrete, then the grid could be the entire domain,but if the function is continuous, its graph must be approximated on a �nitesubset of the domain. To create an evenly spaced, one-dimensional grid, usethe function linspace, which takes as arguments the minimum, the maximum,and the number of points in the grid.

>> x=linspace(0,1,101);

creates a row vector x with 101 elements from 0 to 1 (so that the spacingis 0:01).Next, we evaluate the function on the grid.

>> y=x.*cos(x);

returns x times the cosine of each element of the grid. Observe that it isnecessary to use array multiplication here: "x*cos(x)" is not de�ned becausethe row vectors x and cos(x) are not conformable, and "x*cos(x)�" wouldreturn a scalar. As written, y is a row vector of 101 elements, so we have aproper assignment from every grid point to a unique value. To graph this,use the syntax

>> plot(x,y)

- which causes Matlab to identify x with the horizontal axis and y withthe vertical axis in a standard coordinate system. A new window pops upthat displays the graph, with suitably scaled axes.Suppose now we want several graphs in the same diagram. We could

de�ne a new grid for every graph and evaluate it for the desired function, orwe could evaluate new functions on the same grid. Then the new coordinatepairs are entered as additional arguments when calling the plot function.

5

Page 6: matlab

>> z=x.*sin(x);

>> plot(x,y,x,z)

To add some labels and explanations, call the functions "xlabel(name ofx-axis)", "ylabel(name of y-axis)", "title(title of the diagram)", and "leg-end(name of �rst graph, name of second graph, etc.)". Each of these takestrings as arguments, which must be enclosed in quotation marks.

>> title (�Some Innocent Plottings.�)

>> xlabel(�domain�)

>> ylabel(�values�)

>> legend(�x*sin(x)�,�x*cos(x)�)

By default, the legend appears in the upper right corner, but this - andany other detail - can be controlled by additional commands.If we wanted to graph x against y and x against z separately, it might

be convenient to do it in a single �gure window with multiple plots. Thecommand>> figure(2)

creates a new �gure window, and>> subplot(1,2,1)

instructs Matlab to prepare a 1 � 2 matrix of coordinate systems and workin the �rst "cell" (the �rst plot) for the moment. The plots are numberedleft to right and top to bottom, e.g. "subplot(2,2,3)" refers to the bottomleft lot in a 2 � 2 arrangement of plots. Now that Matlab is looking at theright cell,>> plot(x,y)

generates the graph. Now we direct Matlab to the second cell and �nish thedouble plot:>> subplot(1,2,2)>> plot(x,z)There are many ways to re�ne the plots by selecting speci�c colors, line

styles, etc. All of this can be done through the toolbar in the �gure win-dow, but as you gradually learn the syntax, you will �nd it more e¢ cient toprogram these properties as well.Creating 3-D graphs is simple: just use the plot3 command.>> figure(3)>> plot3(x,y,z)>> grid on

Adding grid lines ("grid on") is not necessary, but tends to improve read-ability.

6

Page 7: matlab

1.4 Polynomial Roots and Approximation

1.4.1 Representing Polynomials and Finding Zeros

An n-th degree polynomial can be written as an inner product of an (n+ 1)-vector of constants and26664

xn

...x1

37775 :For example,

x3 +x

2� 4 =

�1 0 1

2�4

� 2664x3

x2

x1

3775 :The constant vector

�1 0 1

2�4

�contains all the information about the

polynomial: from its dimensions (n + 1 = 4), we can read o¤ the degree(n = 4 � 1 = 3), and then the constants fully describe the polynomial.Matlab uses this property by identifying polynomials with their constantvectors in the relevant prede�ned functions.We do not even have to do all the work of bringing a general polynomial

such as�x2 + 3

� �x2 + x� 3

�(x+ 1)

into the vector product form. The Matlab function "conv(polynomial, poly-nomial)" returns the product of two polynomials:

>> p=conv([1 0 3],[1 1 -3]);

>> conv(p,[1 1])

ans =

1 2 1 3 -6 -9

So

�x2 + 3

� �x2 + x� 3

�(x+ 1) =

�1 2 1 3 �6 �9

�26666664x5

x4

x3

x2

x1

37777775 :

7

Page 8: matlab

The function "polyval (polynomial, x)" evaluates a polynomial at theuser-provided value of x.

>> polyval([1 0 .5 -4],3)

ans =

24.5000

since

x3 +x

2� 4���x=3

=49

2:

This function is most useful when we wish to plot an x series against a yseries that is produced by a polynomial such as a linear regression equation.First create a grid, i.e. a row vector for x, then evaluate it using polyval:

>> x=linspace(1,50,301);

>> y=polyval([1 0 .5 -4],x);

>> plot(x,y)

>> y2=x.^3+.5*x-4;

>> plot(x,y2)

where the two plots are identical because y = y2 from Matlab�s point ofview.It is very easy to �nd roots of polynomials in Matlab, i.e. the values of

x at which the polynomial equals zero. The function "roots(polynomial)"returns all real and complex solutions. For example:

>> roots([1 0 .5 -4])

ans =

-0.7413 + 1.4658i

-0.7413 - 1.4658i

1.4826

Hence x3 + x2� 4 has one real root (1:4826) and two complex roots with

real part �0:7413 and imaginary parts 1:4658i and �1:4658i, respectively.Matlab recognizes the imaginary number i =

p�1.

8

Page 9: matlab

1.4.2 Curve Fitting

There are essentially two approaches for recovering a function from x andy series. One is a regression-type least squares �t, which assumes that thecurve is an n-th degree polynomial and computes the optimal constant vector(the �s, or parameters, in econometric lingo). Matlab�s built-in function forthis purpose is "poly�t(x data, y data, n)", where n is the degree of thepolynomial. Suppose we generate some data by distorting the values of thepolynomial x3 + x

2� 4 a bit:

>> x=linspace(1,50,301);

>> y=polyval([1 0 .5 -4],x);

>> z=2*rand(1,301).*polyval([1 0 .5 -4],x);

>> curve=polyfit(x,z,3)

curve =

2.6221 -10.7316 22.5704 -18.0680

>> plot(x,z,x,polyval(curve,x),x,y);

>> legend(�data�,�fitted�,�undistorted�)

The plot shows the data points z (x), the �tted curve, and the originalgraph y (x). The estimated polynomial, z (x) = 2:6221x3 � 10:7316x2 +22:5704x � 18:0680. Although this looks very di¤erent from y (x) = x3 +0:5x� 4, the plot shows that the two graphs are close.The other method of �tting a curve to two data series is a spline. Whereas

polynomial approximation assumes that one parametric function generatesall sample points, and that deviations from the optimally �tted curve are dueto noise (say, measurement errors), the premise of the spline approach is thatall data points are correct and must belong to the curve. The starting pointin constructing a spline is therefore the sample, which imposes values of thefunction at the points in the domain where data are available. Normally,we cannot then write down one parametric function that holds at all thesepoints. Instead, segments of the function are constructed between individualpairs of data; each segment is a polynomial of degree n, but the parametersvary from segment to segment. The functional form n is determined bysmoothing considerations.A linear spline (n = 1) is discontinuous at the data points, as the segments

are just straight lines between (xt; yt) and (xt+1; yt+1) with slopesyt+1�ytxt+1�xt :

A quadratic spline (n = 2) is discontinuous in �rst derivatives at the datapoints, as the segments are curves of the form y = ax2+bx+c, passing through

9

Page 10: matlab

(xt; yt) and (xt+1; yt+1). The slopes, 2ax + b, are linear, hence nonsmooth.The most commonly used spline is, however, the cubic spline (n = 3), whichis discontinuous in second derivatives at the data points. The segmentsare curves of the form y = ax3 + bx2 + cx + d, passing through (xt; yt)and (xt+1; yt+1). The derivatives of the slopes, 6ax + 2b, are linear, hencenonsmooth, but the slopes themselves are smooth, so the spline function istwice di¤erentiable.To evaluate a cubic spline at a point x in the domain, call "spline(x data,

y data, x)". For example, continuing from before with the distorted series z,

>> spline(x,z,2^(1/2))

ans =

-0.4018

Since x =p2 is not in the grid x, this is an estimate. Compare this to

the polynomial approximation and to the undistorted polynomial:

>> polyval(curve,2^(1/2))

ans =

-0.1952

>> polyval([1 0 .5 -4],2^(1/2))

-0.4645

In this case, the spline does a good job. Suppose, however, we have fewerobservations for z.>> x2=linspace(1,4,51);>> z2=2*rand(1,51).*polyval([1 0 .5 -4],x2);>> spline(x2,z2,2^(1/2));ans =

-0.1459To plot the spline and compare it the polynomial approximation, evaluate

the spline on the entire grid"

>> cspline=spline(x2,z2,x);

>> plot(x,z,x,polyval(curve,x),x,cspline,x,y);

>> legend(�data�,�poly fit�,�spline�,�undistorted�)

Although the spline re�ects the �uctuations in the randomizeddata far better than the polynomial approximation, it admits in

10

Page 11: matlab

many places relatively large errors. ot surprisingly, the polyno-mial approximation does a far better job recovering the originalpolynomial. As a rule of thumb, low-order polynomial approx-imations are preferred when the typical values, rather than theoutliers, are primarily of interest, and features of a smooth un-derlying distribution are to be recovered. A spline is used whenvolatility is to be accounted for and outliers matter, as in muchof the current work in macroeconomic �uctuations. Note thata spline cannot be used with data that are not one-to-one, i.e.where the same x is associated with di¤erent observations of y.By design, the spline would have in�nite slope at such a point,since it must pass through all sample points.

1.5 Help

A keyword search of the extensive Matlab help database can be performedby "lookfor keyword". If information about a speci�c command is needed(for example, how many arguments a function takes, what they are, how it iscalculated), use "help command". It can take a while to execute "lookfor",since Matlab has to do a text search of the entire database.Upon typing "help plot," Matlab will show some of the color and line

style properties that can be speci�ed for plots. To �nd a particular prob-ability density function, try "help pdf," and Matlab will list about twentycommon distributions from which "pdf(distribution name, grid, parameter 1,parameter 2 ...)" calls the frequencies at points in a grid vector you de�ne.

2 Writing Programs

Matlab programs are written in M-�les and executed in the command windowby typing the name of the M-�le at the prompt. (If located in the defaultdirectory.) A new M-�le can be opened by clicking the blank page icon inthe Matlab interface, or by navigating through File >> New >> M-File. Itshould be saved with the ".m" extension.

2.1 Text Output and Input

To print a sentence to the screen, use the syntax "fprintf(�string�)":

>> fprintf(�A Matlab program. The author is anonymous.�)

A Matlab program. The author is anonymous.

11

Page 12: matlab

A line break is made by inserting "nn" into the string:

>> fprintf(�A Matlab program.nnThe author is anonymous.�)A Matlab program.

The author is anonymous.

The newline operator "nn" is also a signal to the computer to print thetext written since the last "nn" to the screen. If a program does not encounter"nn" sometime after fprintf, the text is not displayed when the program runs.If the sentence is to report a value that was calculated by the program, callthe value within the string by the placeholder variable "%g" and assign aspeci�c variable after the string:

>> x=sin(1)

ans =

0.841471

>> fprintf(�Wait a moment while x is calculated.nnx=%g.�,x)Wait a moment while x is calculated.

x=0.841471.

>> fprintf(�e=%gnnpi=%g�,exp(1),pi)e=2.71828

pi=3.14159

The last command demonstrated that, if several values are called in thesame string (by including "%g" repeatedly), then the function assigns the�rst variable to the �rst %g, the second variable to the second %g, etc.To let the user specify the value of a variable, declare the variable as the

value of the input function. The input function takes as an argument thestring that prompts the user to enter a value.

>> tellme=input(�Give me a number:nn�);Give me a number:

3

>> fprintf(�The number you gave me is %g.�,tellme)

The number you gave me is 3.

To request a string value, add �s�after the prompting message:

12

Page 13: matlab

>> tellme=input(�Is lambda > or < than 1 (yes/no)? nn�,�s�);Is lambda greater or smaller than 1 (yes/no)?

yes

>> fprintf([�You answered: � tellme �.�])

You answered: yes.

If the input is matrix-valued, the i-th component is called by "matrix(i)".

>> tellmemore=input(�Enter 3 numbers as [1 2 3].nn�);Enter three numbers in vector format "[1 2 3]":

4 8 6

>> fprintf(�The first number is %g.�,tellmemore(1))

The first number you entered is 4.

To display a vector or a matrix, use the "disp(matrix)" function.

trimat=[0 2 3; 0 0 2; 0 0 0];

fprintf(�The matrix is: �);

disp(trimat);

fprintf(�nn�)

For any but the simplest programs, explanations should accompany thecode. Anything typed after the symbol % (unless inside a string) is ignoredfor the remainder of the line.

>> i=10000 % I was joking. The truth is: i=10.

i =

10000

A standard sort of commentary:

% This program is called "nothing.m"

% and was written by myself.

% It does precious little.

x=0 %/ Declare x.

y=0 %/ Declare y.

fprintf(�Nothing from nothing leaves %g.�, x-y)

% Show the result.

13

Page 14: matlab

2.2 Conditional Constructions and Loops

2.2.1 If

A basic if statement has the format

"if condition

instruction;

instruction;

end"

(where there can be as many instructions as desired). The condition isa statement about one or more previously declared variables, with a logicalvalue of "true" or "false". The instructions are executed if the condition istrue; if not, the program jumps to "end".

x=10*rand(1,1)

if x>5

fprintf(�Have a great day.�);

fprintf(�The charge for this message �);

fprintf(�is %g dollars.nn�,roundn(x));end

The "roundn(number)" function rounds to the nearest hundredth. Forrounding to an integer, the functions "round(number)", "�oor(number)",and "ceil(number)" are available: round returns the nearest integer, �oorthe nearest smaller integer, and ceil the nearest larger integer. Some rela-tional and logical symbols that may be needed to construct conditions forconditional constructions are given below.

== "equals to"~ = "not equal to"<= "smaller than or equal to">= "greater than or equal to"~ "not"& "and"j "or" (inclusive)

xor (�) "or" (exclusive)all (�) all elements are nonzero / trueany (�) some element is nonzero / true

For example, the condition

14

Page 15: matlab

(x~=10 & x>=5) j xor(x<5,x==10)

is always true, hence the subsequent instructions will be executed. And

all([1 0 1])

has a value of zero (false), whereas

any([1 0 1])

has a value of one (true), which implies that

all([1 0 1])~=any([1 0 1])==1.

The string comparison function "strcmp(string, string)" returns 1 if thestrings are the same and 0 otherwise.

>> x=�happy�;

>> y=�sad�;

>> strcmp(x,y)

ans =

0

An if-elseif-else statement has the format

"if condition

instruction;

instruction;

elseif condition

instruction;

instruction;

elseif condition

instruction;

instruction;

else

instruction;

instruction;

end"

15

Page 16: matlab

(where there can be as many elseif clauses as desired). Elseif is similar toa new if clause, except that it informs the program that the condition in anyprevious if or elseif clause in the if statement does not hold. This often avoidsredundancy. Else can only appear once in the statement, just before theend; it instructs the program about what to do when the condition in everyforegone if and elseif clause fails. When an if statement has an else clause,then the if statement always leads to the execution of some instruction, aseither some condition holds or else applies. The if statements we encounteredpreviously, that had no else, may not do anything if the condition is notsatis�ed. We can now re�ne the greetings program:

x=10*rand(1,1);

if x>5

fprintf(�Have a great day.nn�);fprintf(�The charge for this message �);

fprintf(�is %g dollars.nn�,roundn(x));elseif x>2.5

fprintf(�Have an okay day.nn�);fprintf(�This message comes at a special price �

fprintf(�of %g dollars.nn�,roundn(x));else

fprintf(�I�m sorry, but I don�t find it worth my while

fprintf(�to greet you.nn�);end

In the last fprintf line, the repetition of the single quotation mark in "I�m"and "don�t" signals to the program that this is not the end of the string, buta character to be printed.

2.2.2 Switch-Case

A switch-case construction has the format

"variable=input(�prompt�) or random

switch variable

case �rst value

instruction;

16

Page 17: matlab

instruction;

case second value

instruction;

instruction;

otherwise

instruction;

instruction;

end"

(where there can be as many instructions as desired). This type of state-ment is essentially an alternative to if-elseif, with a practical advantage whenthe condition amounts to the value of a variable. Instead of writing every time"if/elseif variable=value ...", we declare at the beginning of the statementwhich variable we are conditioning on (the "switch" command) and then listthe relevant values (the "cases"). The analogue of "else" is "otherwise" here.The following is a program that simulates a game show where contestants

choose among three doors the one that hides a prize. The program declaresan input variable "choice" that stores the number of the door the contestantis betting on. The host then reveals that one of the other two doors doesnot hold the prize and gives the contestant an opportunity to choose againbetween the remaining two doors. Which door can be opened obviously de-pends on which door was initially chosen; we use the switch-case constructionto work through the three possible initial choices. In each case, the door thatwill be opened is uniquely determined if the initial guess was wrong. If theinitial guess was right, either of the two other doors could be opened, so eachcase contains a random assignment in that scenario.

fprintf(�nnWelcome! �);

fprintf(�There are three doors, numbered 1 to 3. �);

fprintf(�Behind one door, a prize awaits.nn�);choice=input(�Choose a door.nnnn�);error=0;

prizedoor=ceil(3*rand(1,1));

success=(choice==prizedoor);

y=round(rand(1,1));

switch choice

17

Page 18: matlab

case 1

if success

if y==0

emptydoor=2;

else

emptydoor=3;

end;

elseif prizedoor==2;

emptydoor=3;

else

emptydoor=2;

end;

case 2

if success

if y==0

emptydoor=1;

else

emptydoor=3;

end;

elseif prizedoor==1;

emptydoor=3;

else

emptydoor=1;

end;

case 3

if success

if y==0

emptydoor=1;

else

emptydoor=2;

end;

18

Page 19: matlab

elseif prizedoor==1;

emptydoor=2;

else

emptydoor=1;

end;

otherwise

error=1;

end;

if error==1

fprintf(�nnYour choice is not valid.�);else

if (choice==1 & emptydoor==2) j (choice==2 & emptydoor==1)offerdoor=3;

elseif (choice==1 & emptydoor==3) j (choice==3 & emptydoor==1)offerdoor=2;

else

offerdoor=1;

end;

fprintf(�nnThere is no prize behind door number %g.�,emptydoor);

fprintf(�You may switch to door number %g.nn�,offerdoor);yesno=input(�Would you like to switch (y/n)?nnnn�,�s�);if yesno==�y�

choice=offerdoor;

end;

if choice==prizedoor

fprintf(�nnYou�ve done it!!! �);

fprintf(�The prize was indeed behind door number%g.nnnn�,prizedoor);

else

fprintf(�nnI�m sorry, you lose. �);

19

Page 20: matlab

fprintf(�The prize was behind door number %g.nnnn�,prizedoor);end;

end

Notice how in this example "otherwise" is used to build in the possibilitythat the contestant makes an error and chooses a door other than 1, 2, or 3.The variable "error" was set to zero (i.e. false) at the outset, but if none ofthe cases obtain, "error" is rede�ned under "otherwise" as 1, which triggersthe message "Your choice is not valid." in the next if statement.Suppose in a switch-case construction several cases have the same set of

instructions. Then we can specify a set of values as one case. For example:

answer=input(�Name a day of the week that starts with T.nn�,�s�);switch answer

case {�tue�,�Tue�,�tuesday�,�Tuesday�,�thu�,�Thu�,�thursday�,�Thursday�}

fprintf(�Yep, that�s one. You sure know your weekdays.�);

otherwise

fprintf(�Either you misspelled the day you meant, �);

fprintf(�or you should take a hard look at your calendar.�);

end

As is evident in this program, the option to nominate alternative stringsfor the same case is often useful when di¤erent spellings may be expected asvalues of the input variable.

2.2.3 For

A �xed number of repetitions of a set of instructions is implemented by a forloop. A for loop has the format

"for index=sequence or set

instruction;

instruction;

end"

(where there can be as many instructions as desired). It is customaryto use i as the index variable. If i is set to an evenly spaced sequence, thesyntax is:

20

Page 21: matlab

"i=start value:increment :end value",

for example:

>> i=0:5:10

i =

0 5 10

If no increment is speci�ed (say, i=0:10), the program uses the defaultincrement of 1. The following loop produces a laugh.

for i=1:3

fprintf(�ha�);

end

The increment can be negative, so that the sequence counts down.In this case, the start value must exceed the end value.

>> i=10:-5:0

i =

10 5 0

If i is a set, then the syntax is:

"i=[value value value]",

(where the index set can contain as many values as desired). For example:

>> i=[0 5 10]

i =

0 5 10

The instructions in the for loop are executed as many times as there arevalues in the index set. The motivation for specifying particular index sets(rather than always using a sequence with increment 1) is that the valuesmay play a role in the instructions for the individual runs of the loop. Thefollowing program, which calculates factorials, illustrates this.

21

Page 22: matlab

fprintf(�nnThis program calculates n factorial (n!).nn�);n=input(�nnSpecify n. nnnn�);factorial=1;

for i=n:-1:2

factorial=factorial*i;

end;

fprintf(�nn%g! = %gnnnn�,n,factorial);

This program uses a standard schema for computing products and sumsin a for loop. Declare a store variable and set it initially to zero (for a sum) orto one (for a product). Then execute a for loop, indexed by the summands orfactors, that contains the instruction to add / multiply by the current indexvalue and update the store variable after every run. Here is a program thatsums the prime numbers below twenty.

sum=0;

for i=[2,3,5,7,11,13,17,19]

sum=sum+i;

end;

sum

Often, for loops are used to calculate components of a matrix. A commonprocedure is to �rst declare an "empty" matrix of zeroes with the command"zeros(rows, columns)", then "�ll" the matrix by using for loops to sequen-tially call and update the individual components. The (i, j)-th component ofmatrixM is called by "M(i,j)" - for example, M(1,4) for the element sittingin the �rst row and fourth column. The next program creates 10�10 matrixthat holds the integers 1 to 100.

matrix=zeros(10,10);

for i=1:10

for j=1:10

matrix(i,j)=(i-1)*10+j;

end;

end;

disp(matrix)

22

Page 23: matlab

In practice, one may not know the dimensions of the matrix at the timeof programming. This happens with econometric routines, where a datasetof unknown size will be loaded or a sample of adjustable size is simulated, orwhen writing any long program where it is tedious to keep track of matrixsizes. For these occasions we have the "size(matrix)" function, which givesthe dimensions of the matrix.

>> x=[1 2 3 4; 3 4 5 6; 5 6 7 8];

>> size(x)

ans =

3 4

>> d=size(x);

>> rows=d(1,1)

rows =

3

>> cols=d(1,2)

cols =

4

Sometimes it is more convenient to work with the "length(matrix)" func-tion instead, which gives only the number of columns (or the number ofcharacters in a string variable). Since this is always a scalar, it saves thetrouble of calling a component. Here is a program that �lls a square matrixof random dimensions with integers from 1 to the the maximum allowed bythe dimensions.

x=ceil(10*rand(1,1));

matrix=zeros(x);

sum=0;

for i=1:length(matrix)

for j=1:length(matrix)

matrix(i,j)=sum+1;

sum=matrix(i,j);

end;

end;

disp(matrix)

23

Page 24: matlab

Finally, consider the following task. The program is to ask for an estimateof � and accept if it is "close enough," otherwise give feedback and ask foranother estimate, granting �ve guesses overall. There are two reason why wedo not want the program to loop through all �ve runs all the time. First, theuser may provide a good estimate before the last round, in which case theprogram should not ask for a new estimate. Secondly, a user who does notknow � may wish to stop the program without guessing �ve times. Theseconditional terminations of the for loop can be built in by means of an if-elseifclause with the "break" command in the instructions where conditions aremet that warrant stopping the loop. In the program below, a break appearsin case the error of the estimate is acceptably small and in case the userenters an estimate of zero to signal that she wants to �nish.

fprintf(�nnPlease write down the value of pi up to thethird decimal place.nn�);fprintf(�You have five attempts.nn�)estimate=input(�nnWhat is your first try? �);

success=0;

prev_error=0;

for i=1:4

error=abs(estimate-pi);

if error<.001

fprintf(�nnCorrect! The value of pi, �);

fprintf(�exact to 14 decimal places, is %16.14f.nnnn�,pi);success=1;

break;

elseif (i>1) & (error<=prev_error)

fprintf(�nnGetting closer! �);

estimate=input(�Try again. �);

prev_error=error;

elseif (i>1) & (error>prev_error)

fprintf(�nnWorse than your last attempt. I thinkyou�re just guessing!nn�);

estimate=input(�Try again. If you would like tostop, enter 0. �);

24

Page 25: matlab

prev_error=error;

else

fprintf(�nnNo, no. �);

estimate=input(�Try again. If you would like tostop, enter 0. �);

prev_error=error;

end;

if estimate==0

break;

end;

end;

error=abs(estimate-pi);

if error<.001

fprintf(�nnCorrect! The value of pi, �);

fprintf(�exact to 14 decimal places, is %16.14f.nnnn�,pi);success=1;

end;

if success==0

fprintf(�nnYou didn�t succeed. Play again.nnnn�)

This program sometimes employs the placeholder "%16.14f" instead of"%g". The two have the same function, namely representing a variable ina string, but "%16.14f." includes speci�c formatting instructions: displaythe variable (in this case, �) with 15 digits, 14 of which after the decimal(the remaining place is taken up by the decimal point). The formattedplaceholder can be adapted to any number of digits after the same pattern.For the present purpose, 15 digits made sense because we wanted to report �as accurately as possible for the user�s information, and Matlab�s double-digitprecision enables it to calculate up to 16 places accurately. If "%20.15f" hadbeen used, so that there are three zero places in front, Matlab would haveinserted three spaces as an indentation. This is sometimes useful when theoutput is to be arranged into a table and column entries have to line up.Matlab never reports a false result because of formatting: if it is given lessdigits in front of the decimal than it needs, it violates the format commandand displays the digits anyway.

25

Page 26: matlab

>> x=10*10;

>> fprintf(�10*10 = %2.0f�,x)

10*10 = 100

>> fprintf(�10*10 = %6.1f�,x)

10*10 = 100.0

2.2.4 While

When a set of instructions is to be repeated as long as some condition holds,a while loop is called for. Such is frequently the case when iteratively ap-proximating some quantity, say a �xed point or roots of a polynomial. Thenthe condition is that the error criterion has not yet been met. A while loophas the format

"while condition

instruction;

instruction;

end"

(where there can be as many instructions as desired). The instructionsare executed if the condition is true; if not, the program jumps to "end". Asan example, here is a program that calculates the best approximation to auser-entered number by a factorial x! and returns x.

fprintf(�nnThis program finds the number whose factorialis closest to n.�);

n=input(�nnEnter n. �);

factorial=1;

i=1;

while factorial<n

i=i+1;

factorial=factorial*i;

end;

if abs(n-factorial)<=abs(factorial/i-n)

fprintf(�The solution is %g.�,i);

else

26

Page 27: matlab

fprintf(�The solution is %g.�,i-1);

end

If the user is to have the option to rerun the program as often as de-sired, we may encapsulate the program in a while loop that tests whether tocontinue (and is initialized by an instruction to continue).

fprintf(�nnThis program finds the number whose factorialis closest to n.�);

playon=�y�;

while playon==�y�

n=input(�nnEnter n. �);

factorial=1;

i=1;

while factorial<n

i=i+1;

factorial=factorial*i;

end;

if abs(n-factorial)<=abs(factorial/i-n)

fprintf(�The solution is %g.�,i);

else

fprintf(�The solution is %g.�,i-1);

end;

playon=input(�nnWould you like to run the program again(y/n)? �,�s�);

end

2.3 Functions

2.3.1 Function M-Files

A function in Matlab is a subroutine that is stored separately as an M-�leand can be called by other programs. A function may not be declared withinanother program, since this type of M-�le is treated specially by Matlab.The general format of a function is:

27

Page 28: matlab

"function y= function name (argument, argument)

% comments

% comments

instruction;

instruction;

y=output"

(where there can be as many arguments and instructions as desired).The function will return the �nal value of y, after all instructions have beencarried out. The name y for the output variable is convention, rather than�xed. Neither this, nor how the arguments are named, has any impact onhow the function is used - when called, the function accepts and returnsspeci�c values in place of the variables. The default practice is to save afunction as an M-�le under the function�s name.Every function M-�le begins with the command "function," which tells

Matlab to grant the program some special privileges. One is that the functioncan accept user input of a prede�ned number of arguments, which are enteredin parentheses after the function�s name. For example,

>> log(10)

calls the standard function "log" and speci�es 10 as an argument. Ofcourse,

>> log(10,6)

would not be admissible, since the function "log" only takes one argument.To verify this, we can always type "help log" and �nd information on howto call the function and what it does. When a new function is written, itworks just the same. The programmer speci�es the number of argumentsand the instructions that lead to a speci�ed type of output. In addition,the programmer provides comments: the comments immediately after the"function" line become searchable via the "help function" command. Forexample, the code

function y=funcy(x)

% funcy(x)

%

% This function was written by 007

28

Page 29: matlab

% and returns a top secret code

% number for x.

y=2*x;

includes comments so that "help funcy" will generate:

funcy(x)

This function was written by 007

and returns a top secret code

number for x.

The above text is also searched for keywords by lookfor. A function canbe called either in a program or in the command window:

>> funcy(5)

ans =

10

In a program:

fprintf(�Here is an electronic dictionary that translates�);

fprintf(�ordinary numbers into 007�s secret code.�);

ordinary=input(�Which number would you like to translate?�);

secret=funcy(ordinary);

fprintf(�The translated number is: %g.�,secret);

fprintf(�With this ingenious device, we shall rule theworld!�);

The following is a slightly more serious function that creates a matrix ofuniformly distributed random variables.

function y=urdmv(d,r,c);

% urdmv(d,r,c)

%

29

Page 30: matlab

% This function generates a matrix of uniform random variables

% in an arbitrary interval.

%

% Arguments:

% d - dispersion, i.e. length of interval

% r - number of rows in output matrix

% c - number of columns in output matrix

y=rand(r,c); % create the matrix

y=d*y; % adjust the interval and display the matrix

Users might appreciate the convenience of generating a row vector by onlyspecifying the number of columns. Then the function has to accept only twoarguments. We can condition the instructions for the function on "nargin",the number of arguments provided by the user.

function y=smart_urdmv(d,r,c);

% smart_urdmv

%

% This function generates a matrix of uniform random variables

% in an arbitrary interval.

% The user can either enter three arguments to create amatrix:

%

% d - dispersion, i.e. length of interval

% r - number of rows in output matrix

% c - number of columns in output matrix

%

% or two arguments to create a row vector:

%

% d - dispersion, i.e. length of interval

% c - number of columns in vector

%

30

Page 31: matlab

% If the number of arguments is neither two nor three,

% the function returns 0 by default.

if nargin==3

y=rand(r,c); % create the matrix

y=d*y; % adjust the interval and display the matrix

elseif nargin==2

c=r; % reassign input variables

y=rand(1,c); % create the matrix

y=d*y; % adjust the interval and display the matrix

else

y=0;

end

The command "return" terminates a function; it is analogous to "break,"which stops a loop. To demonstrate, here is a program that �nds, for any x,the largest smaller number that is positive and divisible by 17. The programtests the numbers x�17; : : : ; x�1 successively for positivity and a conditionwhich implies that the number divided by 17 is an integer. If these hold, thefunction is terminated, so that it returns the current value of y.

function y=divsvt(x)

% divsvt(x)

%

% This function finds the closest positive

% predecessor of x that is divisible by 17.

% If it cannot find such a predecessor,

% then it returns zero.

%

% Argument:

% x

for i=0:16

y=x-17+i;

31

Page 32: matlab

if (floor(y/17)==(y/17)) & y>0

return;

end;

end;

y=0;

Notice that, although syntactically we could have used the "break" com-mand instead of "return" to interrupt the for loop, the function would con-tinue to the last instruction and always return zero.

2.3.2 Recursive Functions

A recursive function repeatedly calls itself in evaluating an expression. Forexample, we could calculate the sum of the elements of an n-dimensionalvector v as follows:

function y=vaddr(v,n)

if n>1

y=vaddr(v,n-1)+v(n);

else

y=v(1);

end

Beginning with the last element of the vector, namely v (n), this functionadds v(i) to the sum of components 1; : : : ; i�1 (which is given by the function"vaddr" evaluated at n = i � 1). At i = n, the function checks that n > 1;then "sees" the instruction x = vaddr(v; n � 1) + v(n); which it cannotevaluate without executing vaddr (v; n� 1) : Then n� 1 > 1 is checked, andif true, x = vaddr(v; n � 2) + v(n � 1) is encountered, so that the functionrefers to vaddr(v; n� 2). The process repeats itself n� 1 times until i = 1;which evokes the instruction under "else," which is not circular and allowsvaddr(v; 1) to be evaluated. From this, vaddr(v; 2); : : : ; vaddr(v; n�1) follow,and vaddr(v; n) can be calculated.The general form of a recursive function is:

"function y= function(argument, argument)

if argument > threshold

instruction;

32

Page 33: matlab

y=transformation(function(argument - increment, argument));

instruction;

else

y=value at threshold ;

end"

(where there can be as many arguments and instructions as desired). Thethreshold is typically 0 or 1, since the value of the function is often knownat one of these points. The instructions include an if clause that rede�nesthe function in terms of itself evaluated at another argument, so that, initerating the function, the argument devolves toward the known point wherethe if condition is falsi�ed and a speci�c value of the function is given in thealternative.Since a recursive approach is often an option in writing a function, we

will examine how it performs in terms of computational e¢ ciency. The most-straightforward non-recursive design to calculate an arbitrary sum would be:

function y=vaddnr(v,n)

sum=0;

for i=1:n

sum=sum+v(i);

end;

y=sum;

The next program tests the speed di¤erence between "vaddr" and "vaddnr".For such purposes, we need the functions "clock" (which takes no arguments)to record the current computer time, and the function "etime(end time, starttime)" to calculate the elapsed time between two clockings.

fprintf(�This program tests the speed of �);

fprintf(�calculating a sum recursively and non-recursively.nn�);fprintf(�100 samples of 200 uniform random variables in[0,1] will be drawn.�)

rtime=zeros(1,100); % Matrix to store recursive clockings.

nrtime=zeros(1,100); % Matrix to store non-recursive clockings.

error=0; % Counter for unequal results.

33

Page 34: matlab

for i=1:100

v=rand(1,200);

t1=clock;

vaddr(v,200);

t2=clock;

rtime(i)=1000*etime(t2,t1);

mrtime=mean(rtime);

maxrtime=max(rtime);

t1=clock;

vaddnr(v,200);

t2=clock;

nrtime(i)=1000*etime(t2,t1);

mnrtime=mean(nrtime);

maxnrtime=max(nrtime);

if any(vadd(v,200)~=vaddnr(v,200))

error=error+1;

end;

end;

fprintf(�nnnnThe results disagreed in %g of the samples.�,error);fprintf(�nnnnThe recursive method averaged %g milliseconds.�,mrtime);fprintf(�nnThe longest iteration took %g milliseconds.�,maxrtime);fprintf(�nnnnThe non-recursive method averaged %g milliseconds.�,mnrtime);fprintf(�nnThe longest iteration took %g milliseconds.�,maxnrtime);

One run of the program resulted in:

This program tests the speed of calculating a sum recursivelyand non-recursively.

100 samples of 200 uniform random variables in [0,1] willbe drawn.

The results disagreed in 0 of the samples.

The recursive method averaged 5.61 milliseconds.

34

Page 35: matlab

The longest iteration took 20 milliseconds.

The non-recursive method averaged 0.4 milliseconds.

The longest iteration took 10 milliseconds.

The non-recursive method is signi�cantly faster, and this is generally thecase. Since the computational cost of recursive functions is high, one usesthem only when necessary, such as in computing functional �xed points.

2.3.3 Local and Global Variables

Since function programs can be called in other programs, the question ariseswhether there is a danger that variables in the main program are inadver-tently modi�ed when a function is executed that uses a variable of the samename. A variable that is recognized as one and the same variable by a mainprogram and by the functions it calls is a global variable. Unless otherwisespeci�ed, all variables in Matlab are by default treated as local variables. Lo-cal variables only have validity, and can only be accessed, in the immediateenvironment in which they are de�ned. Hence, the kinds of variables we haveseen so far cannot cause any havoc as main programs and functions interact.If a variable is de�ned in a function program, then the main program doesnot know it exists, and is oblivious to anything that happens to that variableas the function executes. The main program treats its own variable of thesame name as a separate entity and has complete control over it. Similarly,the function is ignorant of the main program�s local variable of the samename.A variable can be jointly tracked and accessed if it is specially identi�ed as

a global variable in both the main program and the function program. (Thelogic behind the double identi�cation is that you may want some functions torecognize it, but not others.) This is done by the "global variable" command:

global x

This statement does not create the variable; x must still be declared ashaving some initial value. But it alerts the environment where the globalvariable is labeled that, if a variable of this name should come along, infor-mation about its current value may have to be obtained from outside andmust be passed on. As an example, take a simple function such as:

function y=oddlog(n)

x=abs(2*n+1);

y=log(x);

35

Page 36: matlab

and call it in the program

fprintf(�I�m thinking of a number. �);

fprintf(�Let�s see how close you can get.�);

x=input(�nnWhat�s your guess? �);

error=abs(oddlog(x)-x);

fprintf(�You missed by %g.�,error)

Everything is local. One possible run of the main program is:

I�m thinking of a number. Let�s see how close you canget.

What�s your guess? 10

You missed by 6.95548.

Now we declare x as global in the main program:

global x;

fprintf(�I�m thinking of a number. �);

fprintf(�Let�s see how close you can get.�);

x=input(�nnWhat�s your guess? �);

error=abs(oddlog(x)-x);

fprintf(�You missed by %g.�,error)

Run again:

I�m thinking of a number. Let�s see how close you canget.

What�s your guess? 10

You missed by 6.95548.

The result is unchanged because x is only a global variable in the mainprogram, not in the function. Correcting this,

function y=oddlog(n)

global x;

x=abs(2*n+1);

y=log(x);

36

Page 37: matlab

Run again:

I�m thinking of a number. Let�s see how close you canget.

What�s your guess? 10

You missed it by 17.9555.

Now we have a change. The program executes as follows. On being calledon to guess, the user provides x = 10. Then the main program evaluateserror = abs(oddlog(x)�x) and, in referring to the function oddlog, it passeson x = 10. The oddlog program computes x = abs(2n + 1) = 21 andoddlog(10) = log(x) � 3. All this is as before, when the di¤erence wasaccordingly error = abs(3:0445 � 10) � 7: But, now that x is a globalvariable, the main program no longer has x at the input value 10; instead ittakes from the oddlog program the updated value 21 and calculates error =abs(3:0445 � 21) � 17: Declaring x to be a global variable introduces amistake in this case, since the programs were not written with this in mind.In other instances, tracking some variables globally turns out to be sensibleand e¢ cient.

37