Вы находитесь на странице: 1из 34

MATH286 - tutorial notes on MATLAB

These notes are intended to be used while sitting in front of a PC running MATLAB. It is assumed that you have already watched a demonstration of MATLAB and have access via VITAL to lecture slides and other reference material. The recommended MATLAB textbook is MATLAB : a practical introduction to programming and problem solving by Stormy Attaway.

The MATLAB environment

Figure 1 shows the typical MATLAB window with various smaller windows (panes). The most important ones are the Command Window (with the >> command prompt) and the Current Directory window which shows all les and subdirectories (subfolders) in the current directory. It works just like a MS Windows File Explorer window (copying, creating, dragging, dropping, renaming etc). Try

Figure 1: The MATLAB window environment. typing pwd in the command window. You should get the same result as shown in the Current Directory box above the windows. Type ls (and of course the Enter 1

key) and you should see a list of les and folders similar to those appearing in the Current Directory window. Typing dir should give the same result. If for some reason you lose this default window arrangement, select Desktop/Desktop Layout/Default and it should reappear. We will be making considerable use of les (especially ones of the kind filename.m) and will be storing them in directories, also called folders. Just to be clear, most traditional computer systems use the terminology directory for where les are collected. Windows-like software also uses the term folder. These mean exactly the same thing. We discuss les and folders more in section 7.

Typing and executing commands

When you type a command (such as pwd or help ls) at the >> prompt, MATLAB will only execute the command once you have pressed the Enter key. Normally you enter commands, one at a time, on separate lines: >> theta = pi/2 >> stheta = sin(theta) Try the above and see what happens. Now try >> theta = pi/4; ctheta = cos(theta); What happened? Now try >> theta, ctheta You learn several things from this: The symbol ; after a command (usually) suppresses the output from it. You can put more than one command on a line. You can separate commands by a comma rather than a semicolon if you dont want to suppress the output. Just typing the name of a variable like theta asks MATLAB to display its current value.

Finding help

Suppose you cant remember the MATLAB name for the (trigonometric) tangent function or need help about how to nd help? Type >> help tangent What happened? Now try >> help tan and >> help help Any better? If you see a link doc help, try clicking on that. Try clicking on the Help item on the main MATLAB menu. Spend some time playing around with the various help menus. Try searching for some item of maths in the Product Help menu e.g. exponential or matrix product. 2

Variables and assignment of values

You will have gathered that you can assign values to variables in MATLAB by means of a command of the form varname = value, e.g. >> radius = 2.5; This can then by used in a further evaluation and assignment: >> Area = pi*radius*radius Did you get the expected answer? How did it know what the value of was?1 The basic rules for variable names are as follows: Use something memorable (to you and possibly others). The name cant have spaces in it (e.g. my lucky number). The name must begin with a letter. After that, the name can contain letters (upper/lower case), numerical digits and the underscore character (e.g. my lucky number=13). Variable names are case sensitive. Try >> radius=1; Area = pi*radius*radius; >> RADIUS How about: >> area Two lessons from this: MATLAB treats radius and RADIUS as two completely dierent objects. MATLAB indeed treats area as dierent from Area and, in this case, thinks you are trying to use a built-in function called area. (Type help area to check this). To see what variables you have used (are still using) use the command who. Try the following: >> who >> clear >> who >> radius=2.0 >> who Have you been noticing what is going on in the Command History window as you have been typing? If you double-click on one of the previous commands, MATLAB will re-execute it. If you get tired re-entering commands, or ones very like them, you can use the up-arrow on your key board () to cycle through these previous commands. You then have the opportunity to make changes to them before pressing Enter in order to execute the new edited version. Try typing
1

pi is an example of a built-in variable or function. i (=

1) is another one

>> MyName=Joe Bloggs Now use the up-arrow and then left-delete key () to correct it to display your real name. Did you notice that we assigned a string value rather than a numerical value to the variable MyName? We will discuss strings and characters in section 12. Try assigning the sentence: Are you over the age of 18? to the variable agequest. Did you remember to enclose all the words and symbols in single quotations marks? Try it again leaving out the nal quotation mark.

Output format

Do you nd the extra blank lines in MATLAB output annoying? Try typing >> onerev=2*pi >> format compact >> tworevs=4*pi Did you notice the dierence? Typing format by itself returns MATLAB to its default display format. Not enough digits? Try >> format long >> tworevs Better the way you were? Try >> format short >> tworevs Dont forget to use the up-arrow key when you re-try things. Have a look at help format.

Operators and brackets

Evaluating mathematical expressions in MATLAB is pretty well as you would expect it to be. Some examples to type in: >> a=5;b=-2.5;c=0.14;d=4.1;n=4; >> ex1=(a+b)*c >> ex2 = (c-b) / (a-b) >> ex3 = (a/b)^n + (c-d)^2*n >> ex4 = (a-2*b)*(a/(c+d)) >> ex5 = (((a-2*b))*(a/(c+d))) >> ex6 = (((a-2*b)*(a/(c+d))) 4

Some remarks on these: Did the last one (ex6) work OK? Can you see why not? Addition and subtraction operations are as expected. Multiplication and division operators are usually just and / but we will come back to this when we discuss vectors and matrices later in section 8. The operator precedence rules are just the same as in mathematics (recall the mnemonic BODMAS?).2 If in doubt put in some brackets to make sure things happen the way you intend. Extra brackets dont do any harm (e.g. ex5), provided they are correctly paired (c.f. ex6). Spaces in assignments are not signicant (c.f. ex1 and ex2).

Files, folders and directories

A typical calculation using MATLAB can involve a lengthy sequence of commands, for example assigning some initial values to variables (section 4) and then working out some mathematical expressions using these (section 6). Even making use of the up-arrow trick, it can then be tedious to repeat the calculation using dierent values, or with a corrected expression, or in some modied form at a later date when all trace of the calculation has been lost. This is where the creation of script les, also known as M-les comes to the rescue. In fact, a simple M-le is an example of a straightforward computer program written in the language MATLAB (c.f. C, Fortran, C++, Java, Basic, assembler). Try the following. Type >> edit and you will see the MATLAB editor open up showing a blank M-le called untitled.m. Now enter some lines of MATLAB : % this script will be called mycylinder.m radius=233; height=11.4; crossarea=pi*radius^2 volume=crossarea*height Note that there is no command prompt within the M-le. The commands will be executed line by line, as we show later. The line beginning with % is just a comment line which does not get executed more on this later. When you have done that, use File/Save As from the editor menu to save it as mycylinder.m. You will notice that the editor window name has now changed to reect the new name. In future if you wanted to edit the le you could type
Brackets, Orders (Powers, Square Roots), Divide and Multiply (left to right), Add and Subtract (left to right).
2

>> edit mycylinder.m Now to execute these commands as saved, type >> mycylinder Do you notice the exponential format used to display the large values? (Use help format to read more about this.) If you type >> who you will see that the variables assigned in this script le are still known to MATLAB and you can carrying on using them if you want: >> surfacearea=2*pi*radius*height Now use the editor to change the radius to 13.2 and the height to 1.234. If it is not already open in the editor, simplying double-clicking on the lename will open it. When you have changed the relevant line(s) in the le mycylinder.m, you use File/Save from the editor menu (or the little blue oppy disk Save icon) to re-save it. Using the little blue Save icon is a good way to do it as you see it go from blue to grey as the save is actually made. If you re-run mycylinder.m by typing >> mycylinder you should get new values for the results. If you didnt, are you sure you saved the le after making the changes? The little Save icon should be grey and not still blue! You (may) have written your rst program! If you simply keep creating and storing more and more les, you very quickly create a mess and are unable to nd anything anymore. Lets suppose your Current Directory window shows that the current directory is M:\matlab or M:\matlab32 With the mouse cursor over that window, right-click and select New Folder. Rename the folder to be tutorial or some such name. Now select/drag the le mycylinder into the folder tutorial. Now type >> cd tutorial >> ls Did your script-le get listed as present in this new directory? Is the Current Directory window (and box on the menu) now showing M:\matlab\tutorial? Now try >> cd .. >> ls What happened? From now on when you create les, you should be careful to store them somewhere sensible where you can nd them later and re-use them. It also helps if you can remember what purpose it served! There are a few key steps you can take to help with this. 6

Use a meaningful name for the le (i.e. not myfile.m or test.m). Keep related les in one folder. Make good use of comments. These can be a complete line of text starting with the symbol %, or some text (starting with symbol %) appended to a line containing a MATLAB command. It is good practice to have a few lines of comments (text lines all starting with %) at the beginning of the le which then have a special purpose - they get displayed when one types e.g. help mycylinder. Now nd and edit your le mycylinder so that when you type help mycylinder, it displays >> help mycylinder This file is called mycylinder.m It finds the cross-sectional area and volume of a cylinder of specified radius and height. Also try putting in a comment on the line: crossarea=pi*radius^2 % this is the area of a circle Notice that, unlike the block of comment lines at the beginning of the le, such comments are only seen in the editor and not when one uses help filename. You can also see the full text of a script le, including both code and comments, by typing e.g. >> type mycylinder

Vectors and matrices

The name MATLAB is derived from MATrix LABoratory. Much of the power of MATLAB comes from its ability to manipulate matrices (and vectors) in a very natural way. MATLAB also has the ability to perform calculations for several dierent values at once by treating variables as vectors. For example, by creating a vector x of angles we will see that the one MATLAB command sin(x) gives a vector of values of the sine of all these angles. More about this below.

8.1

Matrix products

If the m n matrix A has elements aij and B (n l) has elements bjk then the matrix product C AB is given by
n

cik =
j=1

aij bjk . 7

To evaluate this sum for every one of the ml elements ci,k takes a bit of work with a calculator or simple programming language. In MATLAB , once A and B are known, one just types >> C=A*B Thats it. The operator is clever enough to use appropriate matrix multiplication rules when matrices are involved, and standard arithmetic multiplication when the variables are just simple number-valued (i.e. scalars). Vectors are handled in exactly the same way since they are, in eect, 1 n matrices (row vector) or n 1 (column vector). A dot (i.e. scalar) product can be formed using as a row vector times a column vector with the same number of elements. In order to get a feeling for matrix operations, create a new M-le called matex1.m with the following initial content: % matex1.m % some sample matrix multiplications A = [1 0 2; -2 4 5; 1 1 3] B = [ 1 2 3 4 5 6 7 8 9] V=[3, 5, 6] W=[0 2 4] C=A*B D=A.*B Z=V*W AT=A Q = W*V Run the the le. Now some comments and questions. Notice how A and B are both 3 3 matrices but seem to be entered dierently? Notice that V is a 1 3 matrix (row vector) and rather then having elements separated by spaces there are some commas in there. It looks like elements within a row can be separated either by spaces or commas. What about separating the rows themselves?3 You can see that A is the transpose of matrix A - i.e. the rows and columns have been interchanged. Can you see what the relationship is between Z and Q in this example? Note we could have dened W using the transpose notation equally well with
Comparing A and B you see that you should either use a new line (Enter) or keep typing but use a semicolon as row separator.
3

W=[0 2 4] A new feature illustrated here is the multiplication operator .. Matrices C and D are not the same. C is the matrix product discussed above while D is a new matrix with the same size as A and B formed from the element-by-element product using .. Check each of the elements in D and see if you can see why it has that value. Now edit matex1.m putting in some comments explaining what each line does.

8.2

Creating vectors and matrices

Is there any way to create a vector without having to type in each element? The latter can be especially tedious when you know that the elements have some regular pattern. For example, type >> V = linspace(0,1,5) >> W = 2.5:0.5:20 >> Z = (-1:2:11) Type help linspace to check that you have understood what this command does. How about W? Why does it say Columns . . . through. . . ? W has been created as a row vector (1 n matrix). What is n here? When n is too large to display the full row in one line, the matrix is broken up into chunks which t the current command window. Try dragging the side of the command window so as to make it bigger or smaller, then display W again. >> W Did the the number of columns displayed at a time change? Note the construction of the column vector Z as the transpose of a row vector. What does the matrix >> newmat = [ 1:2:9;2:2:10] give? Can you work out what the following matrix is? >> a=[1,0,0]; b=[0;1;0]; c=[0 0 1]; >> anothermat = [a b c] Write it out on a piece of paper and then check it out in MATLAB . So, it is quite easy to construct matrices out of vectors (as rows or columns) as well as by entering individual elements. Obviously, when using rows (or columns) they need to be of the same length. Have you looked at the Workspace window recently? There, you will see a summary of matrices (vectors) which you have created. Type

>> >> >> >> >>

size(V) length(V) size(newmat) help length help size

The command size is a very useful for checking the number of rows and columns in a matrix. What do you think >> q=[] creates? Check size(q). It is an empty vector. It can be used (see section 8.5 below) to help build up other vectors. It is probably time to clear out the variables used so far >> clear The Workspace window is now empty. The command who also conrms that all your variables have gone.

8.3

Special matrices

MATLAB has a few special matrices which we will be using in a number of dierent contexts: >> >> >> >> a=zeros(3,4) b=zeros(3) c=ones(4,2) d=eye(4)

Suppose you just want some (literally) random matrix to work with. Try the following, in order >> >> >> >> >> A = randi(5,7,3) B = randi(10,4) B = randi(10,4) C = randi(10,4)-5*ones(4) help randi

Some conclusions from this: randi(imax,m,n) gives a (pseudo)random m n matrix of positive integers between 1 and imax. When you re-run the same command (see B=randi(10,4)) above you dont get the same numbers. If you are interested in integer values in a dierent interval (see C above), you can arrange this. You can generate random matrices with non-integer values. Try 10

>> R = rand(5) >> R10 = 10*rand(4) >> a = -4; b=4; >> r= a + (b-a)*rand(5,3) What do these do?4 Have you looked at help rand? We will be discussing random variables much more in Semester 2. MATLAB has a whole range of (almost) random matrices with specic properties. Type help gallery.

8.4

Matrix and vector indexing

We will sometimes want to extract information from vectors and matrices as well as modify them. >> M = [0 1.1 11.4; 4.3 2.1 15.3; 3.1 1.9 13.8; 2.0 0 10.5] >> x = M(:,1) >> y = M(:,2) >> z = M(:,3) >> p2 = M(2,:) As you can see M(:,2) picks out the second column of M while M(2,:) picks out the second row. Now try >> C = M(2:3,2:3) >> D = M(3,2:end) >> R = M(4:-1:1,:) Can you gure out what these matrix index tricks do? Note that end as an index label always refers to the last row or column, working from top to bottom and left to right. The vector notation a:h:b works even when h is negative! So you can use that to reverse the order of matrix or vector elements. Try creating a column vector of integers counting down to zero from 100?5 You can change particular elements of a matrix with a suitable assignment. For example, suppose we want to replace the third row of M with the vector [-3.1 1.9 20.2] we could use >> M(3,:) = [-3.1 1.9 20.2] Notice that, if the output is not suppressed, MATLAB will display the whole of the changed matrix M. Now try >> A = [M(1,:), M(2,:), M(3,:), M(4,:)] >> D = A-M Did you follow what went on there?
4 r here is a 5 3 matrix of random numbers uniformly distributed in the interval (4, 4). The constant a gets added to every element of the matrix. 5 >> backwards = (100:-1:0) or >> backwards = [100:-1:0]

11

8.5

Extending vectors and matrices

Clear your workspace again (>> clear). Having dened a vector of given length e.g. >> primes = [2 3 5 7 11] it is simple to extend it: >> primes = [primes 13 17] Or indeed: >> >> >> >> evens evens evens evens = = = = [] [evens 2] [evens evens(end)+2] [evens evens(end)+2]

Use the up-arrow to continue this if you want. Also try >> fib = [1 1] >> fib = [fib fib(end-1)+fib(end)] >> fib = [fib fib(end-1)+fib(end)] Again, use the up-arrow to re-run the last command a few times.6 The same procedure can be used to extend a matrix: >> >> >> >> >> x = 1:6 xsq = x.*x M = [x xsq] xcube = xsq.*x M = [M xcube]

8.6

Other vector and matrix manipulations

We have already met element-by-element multiplication a.*b, where a and b are matrices (vectors) of the same size. In the last example of the last section we could equally well have obtained x2 and x3 with >> xsq = x.^2 >> xcube = x.^3 Similarly, for division: >> dist = [3 4.5 8 9.5] >> time = [3 5.6 11.4 15.8] >> averagevel = dist./time This processing of multiple values can save quite a bit of eort. Many of the built-in functions in MATLAB can handle vector-valued variables without complaint:
6

This is generating the so-called Fibonacci sequence.

12

theta = [-pi:pi] y = sin(theta) x=(-2:0.2:2) pnormal=(1/sqrt(2*pi))*exp(-x.^2/2) Can you write two commands which will evaluate the quadratic polynomial y = 2x2 7x + 3 for 20 x-values between 0 and 4?7 Try plotting the graph: >> plot(x,y) Does it pass through the x-axis at 0.5 and 3? We will discuss the plot command more in section 14.

>> >> >> >>

8.7

Vector and matrix norms

You will be familiar with the idea of the magnitude of a 3D vector e.g. v = 2i 5j + k , |v| = 22 + (5)2 + 12 = 30 .

This is an example of a vector norm. Try this in MATLAB : >> v = [2, -5, 1] >> magv = norm(v) >> w = [1 -1 2 2 3] >> magw = norm(w) >> A = [1 2 3 4; 5 6 7 8; 9 8 7 6] >> normA1 = norm(A,1) >> normAf = norm(A,fro) >> help norm So, for vectors, norm is still just the magnitude of a vector but with any number of elements. For matrices, there are a number of dierent norms in use. We will usually just be making use of the one for vectors.

Matrix inverse

Try this in MATLAB : >> A = [3 2 1; 4 5 -2; 0 2 1 ] >> b = [1 -1 1] >> P = inv(A) >> Q = P*A >> R = A*P >> X = A\b >> Y = inv(A)*b Did you recognise the matrices P and Q? Now check out help inv and doc inv. If you actually require the inverse of a matrix A, you use the command inv(A). If you simply want to solve the matrix equation AX = b you use the MATLAB command A\b.
7

x= linspace(0,4,20), y=2*x.2-7*x+3

13

10

Script le editing and de-bugging

In section 7 we already showed how to edit a script le (or M-le). Look again to see if you can nd mycylinder.m and matex1.m. Did you manage to create and run these successfully? The chances are that you mistyped something and when you ran them using e.g. >> matex1 there was some mistake which you then had to correct. This was probably also the case when you were typing directly in the command window. The more complex the task, the more likely it is that there will be mistakes. It is therefore a good strategy in such cases to put the commands in a script le which can be run, and repeatedly corrected, until it does what it is supposed to do i.e. it is debugged. Lets create an M-le with some deliberate errors in it and try to correct it using the editor. This will be a key skill when it comes to designing algorithms (programs) as discussed in section 11. Start a new le called matex2.m containing the following lines. Try to copy them exactly (verbatim) even if you already know they are wrong! Perhaps you can copy/paste these lines from the on-line version of these notes.8 % matex2.m % this piece of code works out the angle (in degrees) % between two 3D vectors a = [13; -1; 4] b = [5; 3: 3] adotb=a*b; moda=sqrt(a*a); modb=sqr(b*b); costheta=adota/(moda*modb) theta=acos(costheta) theta=theta*360/pi When you run this >> matex2 you will get a red error message. This is dierent from an orange warning message which you may have seen in the editor window. In the latter case, if you hover the mouse cursor over it, you will get some advice (such as use a semicolon to suppress output !). A red error message causes MATLAB to actually stop running your le. It doesnt mean you have only this one error. This is just the rst one it has found, working down the le, and it needs to xed before proceeding to nd more. If you have typed exactly the above, the complaint will be to the eect that a and b have the wrong dimensions to form a product. Look at a and b:
Copy/paste from a .pdf le works ne apart from the odd special character such as apostrophe () which will need to be corrected by hand.
8

14

>> a, b Note that when you double click on the underlined part of the red error, the editor takes you directly to the oending line. Actually, the problem was earlier. b seems to be a 2D column vector because in line 5, a semicolon was wrongly typed as a colon! Fix this and re-save matex2.m. Re-run it. Still an error! To get the dot product you want a*b since (1 3) (3 1) gives the scalar 1 1. Fix that and re-run. Another error?! This time it may complain about the use of sqr. Should have been sqrt, so x it and re-run. Woops, adota should have been adotb. Fix and re-run. OK now? Well, no actually. There is still one bug in matex2.m. The last line should have been theta=theta*180/pi. The red errors are syntax errors which MATLAB will spot. The last mistake was a logical error which is down to you, the programmer.

11

Algorithms

So far the script les (programs) have simply involved assignment and evaluation of expressions. Along the way, we have encountered a few built-in functions. To perform more complicated tasks such as implementing algorithms, we need to introduce commands which allow choice and allow repetition. The need for repetition in calculations/algorithms is fairly obvious. Choice is also important since, in many calculations, we do dierent things in dierent situations. Think about the solution of a real quadratic equation for example. Choice is handled by the if-else-end type of construction. Repetition is handled by for and while loops.

11.1

Using if-else-end

Create a le matex3.m with the following context. (Read it before and after copying.) % matex3.m % example of if-else-end a=2; b=4; c=-2; % quadratic eqn coeffts disc = b*b-4*a*c; % discriminant if disc > 0 % distinct real roots x1 = (-b + sqrt(disc))/(2*a) 15

x2 = (-b - sqrt(disc))/(2*a) else if disc == 0 x1=-b/(2*a) % equal roots x2=x1 else disp(no real roots); end end Run it. Correct any syntax errors due to typos. Did you nd 2 distinct real roots x1 and x2? Edit the le (changing a, b and c) so as to verify that it correctly solves the equal-roots case? Comment out the current values so you can go back to them later if needed. Re-edit matex3.m to demonstrate a case that should have no real roots. Did you notice how the message no real roots was produced? Can you add in similar messages to accompany the output values in the other cases? We will be discussing more output techniques later in section 13. There are some further important things to notice about the code in matex3.m: The if-else-end construction within is used twice. The second occurrence is nested within the rst. When testing for equality (here if disc is equal to zero) the operator to use is ==. This is because the operator = is already used for assignment. When testing with if, one does not have to include an else option if there is no need. In that case one just uses if . . . end. The result of a test such as dics > 0 is treated as a logical variable. It is either true (1) or false (0). One can combined logical variables using the andoperator (&&) and the oroperator (||) as appropriate. Try the following: >> x=3; y=-2; >> if x>0 && y>0 z=1 else z=-1 end Now repeat this but replacing the && operator with the || operator. Did you follow why the result was dierent?

16

11.2

Using for and while loops

Lets imagine that we want to adapt the script le matex3.m to process several quadratic equations at once. So, make a copy of matex3.m renaming it as matex4.m. The simplest way to do this is to open matex3.m in the editor and use Save As (matex4.m). The original le will still be there. Remember to update the comment lines accordingly. Replace the line a=2; b=4; c=-2; % quadratic eqn coeffts with a=[1 2 -1 1 b=[-1 -14 0 -6 c=[-2 24 -1 10 5/6 4.5]; % quadratic eqn coeffts -4 -12.15]; 4.8 8.1];

Now set up a loop over the 6 quadratic equations represented by the above coefcients. The loop has the form n=length(a); for m=1:n ... end Note that each value of a,b,c now needs to be obtained as an element of the vector: a(m), b(m) and so on. The rest of the code therefore has to be slightly edited to give: n=length(a); for m=1:n %loop over quad eqns disp(solution for eqn), disp(m) disc = b(m)*b(m)-4*a(m)*c(m) % discriminant if disc > 0 % real roots x1 = (-b(m) + sqrt(disc))/(2*a(m)) % distinct x2 = (-b(m) - sqrt(disc))/(2*a(m)) else if disc == 0 x1=-b(m)/(2*a(m)) % equal roots x2=x1 else disp(no real roots); end end end %end of loop over eqns Some comments: Notice that we dont need to save values of disc, x1 and x2 as we loop over the equations. If we did, then we could set up something like disc=zeros(1,n); x1=disc;x2=disc 17

and use disc(m)=.. x1(m)= etc. Note the re-use of the initialising vector for disc. The output lines provided by disp(...) are not very sophisticated. We will improve on this in section 13. In section 15 we will show another way, using a Function M-File, of solving several quadratic equations using just one piece of code. In the meantime try writing yet another exercise le (matex5.m) containing the following key lines of code: X=[ 1 3 -5 -1]; A=[-2 1 0 0 ; 3 4 7 -2; 1 0 0 [m n] = size(A); Y=zeros(5,1); for k=1:m for l=1:n Y(k)=Y(k)+A(k,l)*X(l); end end Y disp(Expected answer is:) Y1=A*X 1; 6 7 -2 0; 5 3 1 0];

together with some appropriate comment lines, of course. These lines evaluate, by brute force, the matrix times vector product y = Ax and compare with the answer obtained using the MATLAB operator *. Notice the way all the elements of Y are set to zero rst. Each element of Y is then calculated one at a time in the outer loop (over k) by adding up all the n contributions to it using the inner loop (over l). So now you have seen how to use for loops, including nested loops, but can also appreciate how sometimes (as in this last example) you can avoid using loops explicitly by using the built-in matrix-handling power of MATLAB . What if you dont know hom many iterations or repetitions will be needed? Have you looked at help while? Describe (write down) on a piece of paper what you think the the following piece of code will do and what the value of the variable n will be after it is run? N=100; K=17; n=N; found=0; while found==0 if mod(n,K) == 0 found=1; else n=n-1; end end 18

Now put the code in a script le, edit in some comments based on what you have written. Then run it and check to see if you were right.

12

Characters and strings

We may have occasion to use strings of characters, particularly when printing output calculated using scripts and functions. More about input and output will be covered in the next section. A character is best thought of as an individual letter that can help make up a word. It can also be a numerical digit (0-9) or one of the various special characters that you nd on a typical computer keyboard ( , *, &, $, space, etc). A string is a just a vector of such characters and so can be used, for example, to represent a word or a sentence complete with punctuation. When assigning characters to a string, one encloses them within quotations marks: myemail=JoeBloggs2@coldmail.com One can: * Use length to see how many characters are in a string; * Concatenate two strings to make a longer string; * Pick out specic parts of a string; * Compare two strings to see if they are equal; * Find substrings within a string. Here are some things to try. >> module=MATH286: Numerical & Statistical Analysis with Programming >> nchars=length(module) >> code=module(1:7) >> words=The module code is >> words=[words code] >> sbegin=1234 >> smore=5678; >> snew=strcat(sbegin,smore) >> smore=[sbegin smore] >> if strcmp(snew,smore) disp(these are the same); else disp(these are not the same); end Did you spot the slight subtlety in the two ways of concatenating strings? 9 How about strings containing lines of words? For example, suppose you wanted to store your module registration for the semester. Try the following: >> regist=[MATH286; ENG201; ENG202;ENG203] Did you get an error message? This is because MATLAB stores the elements of the string as a matrix with each substring (here the module code) as a row. The rows need to be of the same length. So try again (up-arrow) but with ENG
9

strcat removes trailing blanks in a string

19

replaced by ENGG. You can use size(regist) to verify that this string is indeed represented by a matrix of characters. What would you expect regist(2,:) to contain? Check it. Suppose you have calculated some integer value, for example >> secs_in_day=24*60*60; and want to display this result using a string? Try the following >> disp([there are secs_in_day seconds in a day]); It wont work. This is because you need to convert the value of secs in day into a string so that you can concatenate it with the other strings. So, try instead >> disp([there are int2str(secs_in_day) seconds in a day]); Have a look at help int2str. There are other ways to create decent-looking output with a mix of strings and numerical values as discussed in the next section.

13

Input and output

Often you want to have a script (M-le) that inputs some data and then outputs some results on the screen. Create a new script le matex6.m as follows: % matex6.m % example of input and output % based on matex3.m % solves a given quadratic equation disp( Enter the coefficients for ax^2+bx+c=0); a=input(Coefft of x^2: ); b=input(Coefft of x: ); c=input(Coefft of 1: ); disc = b*b-4*a*c; % discriminant if disc > 0 % real roots x1 = (-b + sqrt(disc))/(2*a); % distinct roots x2 = (-b - sqrt(disc))/(2*a); fprintf(The two real roots are %.4f and %.4f\n,x1,x1); else if disc == 0 x1=-b/(2*a); % equal roots x2=x1; fprintf(There is one repeated root: %.4f\n,x1); else fprintf(There are no real roots\n); end end 20

If you are creating this by editing matex3.m, note the extra semicolon after each assignment statement for x1 and x2. This is because we are using the fprintf command to display the values instead. Run it. Some comments: The use of input to both assign the value as entered and to provide a suitable prompt is straightforward. Take a look at help input to nd out more. The command fprintf can provide some quite sophisticated output formatting. The rather strange syntax is because it is just taken more or less directly from the programming language C. Dont confuse the string placeholder % with the same symbol also used for comments in MATLAB . The last entry in the printed string \n ensures that a new line is taken in the output at that point. This is usually what you want. Some other examples of the placeholder being used in fprintf: >> >> >> >> m=5; rad=2.4; area=pi*rad^2; object=circle; fprintf( I have %d fingers in each hand.\n,m); fprintf(The value of pi to 7 decimal places is %.7f\n,pi); fprintf( The area of a %s of radius %.4f is %8.3f\n,object,rad,area);

%d is used to print an integer value. %s is used to print a string. %m.nf is used to print a non integer (oating point) value such that the overall eld width is m and there are n decimal places after the point. In the last example m = 8 and n = 3. You dont have to specify m (c.f. %.4f in the same example). Often, when you dont know how large the number will be, it is best to omit m. However, sometimes (e.g. when creating a table of numbers) you want to ensure things line up nicely and so should give both m and n. Try editing and re-running the above examples to see the dierent eects you can create. Take a look at help fprintf.

14

Plots
f (x) = e1.2x cos(5x)

The function is typical of the solution of a damped harmonic system. As indicated in section 8.6, we could plot this between x = 0 and x = 3 using the commands >> x=0:0.1:3; y=exp(-1.2*x).*cos(5*x); >> plot(x,y) Now create the following script matex7.m containing the slightly more elaborate set of commands: 21

% matex7.m % example of 2D plotting x=0:0.1:3; y=exp(-1.2*x).*cos(5*x); yupper=exp(-1.2*x); ylower = -yupper; plot(x,y,b-,x,yupper,g--,x,ylower,g--); xlabel(x); ylabel(f(x)); title(damped harmonic solution); Run it and use help plot and/or doc plot to see more details of the syntax. Here we are plotting three functions on the one graph. The one in blue (with solid line) is y = f (x) itself. The two dashed curves in green are the upper and lower bounds of f (x) given by y = exp(1.2x). The xlabel, ylabel and title commands are self-explanatory. Suppose you wanted to see more clearly where f (x) crosses the xaxis? Try adding in an extra command grid on after the other commands. You can remove the grid with grid off. To get rid of the extra window containing the graph (by default, labelled Figure 1), just click on the symbol in the usual way. The command clf clears the current gure window but does not close it. As an exercise, try creating a version of matex7.m which shows 3 sin(2x + 1) (in red) and 4 cos(3x) (in yellow) on the same graph.

15

Functions

You have already encountered examples of functions in MATLAB . Some of them, such as sin and size, are built-in and you cant easily nd out how they work. Try >> type sin >> type size Others, such as strcat, trace or factorial for example, are provided as socalled Function M-les (FMFs). Try >> type factorial or >> type trace. What distinguishes an FMF from a script M-le is that it accepts input arguments and, following a calculation using these internally, provides output arguments. The term argument here just means a MATLAB variable with some value assigned to it. Look at trace for example (type trace). There is one input argument (a square matrix) and one output argument (the trace i.e. sum of the diagonal elements). Internally (i.e. within the function), these are known as A and t respectively. For the function to be useful one should be able to use it with any square matrix and assign the output value of the trace to any variable one chooses. Try 22

>> sqmat=[1 2 3; 4 5 6; 7 8 9] >> sqmat_tr=trace(sqmat) Much of the power of a computer programme (including those written in MATLAB ) comes from the ability to construct lots of subroutines, like the MATLAB functions, each with a specic purpose. By combining them together one can then solve increasingly complex problems. One can (re-)use them in a variety of situations so avoiding having to re-invent code from scratch for every problem. As well as using the functions already provided in MATLAB and its associated toolboxes, one usually has to write some of ones own for the particular problem in hand. These are called user-dened functions. You can start to create your own as follows: In MATLAB select File/New/Function and so generate a new FMF template which looks like: function [ output_args ] = Untitled1( input_args ) %UNTITLED1 Summary of this function goes here % Detailed explanation goes here end Take a look at (open in the editor) your script le mycylinder.m. You can edit the FMF template to create a FMF version of this script which inputs the radius and height of a cylinder as input arguments and returns the crossarea and volume as output arguments: function [crossarea volume] = mycylfn(radius, height) Make sure you also edit the comments appropriately and insert the assignment lines crossarea=... and volume=.... Put in semicolons after each assignment to suppress the output within the function. Save the le as mycylfn.m. Now type >> r=34; h=13.2; >> [carea vol] = mycylfn(r,h) >> rad=0.3; ht=0.5; >> [carea vol] = mycylfn(rad,ht) Did it work OK? Note that the names of the variables being passed to and from the FMF are arbitrary. Within the FMF they must be used consistently. Within a script, or on the command line, any variable must be assigned a value before being used. Within a function there is this additional way of giving a variable its value. It can get its value as an input argument. Finally, in this section lets return once more to the quadratic equation example and see how we can turn the code into a FMF which can be called from a script so as to solve any given real quadratic equation or give an error message if it has no real roots. The structure will be: 23

main script M-file (matex8.m) inputs a,b,c from user passes these values to FMF (quadsolve.m) as input arguments receives back the two roots, if any, from the FMF prints out the answers FMF (quadsolve.m) solves quadratic eqn ax^2+bx+c=0 inputs: a,b,c outputs: x1 and x2 or error message if no real roots. We can base matex8.m and quadsolve.m on matex6.m. For matex8.m: % matex8.m % driving script to solve quadratic equation % calls quadsolve.m disp( Enter the coefficients for ax^2+bx+c=0); a=input(Coefft of x^2: ); b=input(Coefft of x: ); c=input(Coefft of 1: ); [r1 r2] = quadsolve(a,b,c); fprintf(The two real roots are %.4f and %.4f\n,r1,r2); For quadsolve.m we could have: function [ x1 x2 ] = quadsolve(a,b,c) % quadsolve.m % finds real roots (if any) of a quadratic eqn disc = b*b-4*a*c; % discriminant if disc >= 0 % real roots x1 = (-b + sqrt(disc))/(2*a); x2 = (-b - sqrt(disc))/(2*a); else error(no real roots); end Create these as best you can by editing matex6.m or copying and pasting the above text. Now run the code by typing >> matex8. Debug it. You will need to type in the coecients for the quadratic equations when prompted. Use the following three examples to check it out: 2x2 x 3 = 0 x2 6x + 9 = 0 x2 + x + 1 = 0 Some notes on this code: 24

(1)

In this simple example there is not a lot to be gained by splitting the task into 3 parts (input, calculation, output) where the main calculation is performed by the function. But note that this function, now tested, can be used as part of a larger calculation where real roots are needed. The variables given as input may of course be named dierently but the function will work unchanged. In order to make a function useful in a variety of circumstances, it is normal practice to return all required results via the output arguments (here x1 and x2). It is then up to the calling script (here matex8.m) to display or, process further, the results. In practice, one function might well be called by another which, in turn, is called by some main or driver script le. It is not normally good practice to dene a function which requires input directly from the keyboard. One should pass in required variable values via the input arguments. We may discuss alternative scenarios later in the module. Unless special arrangements are made (discussed later), any other variables dened within the function are known only within the function and not outside. For example disc is undened (has no value) outside quadsolve.m. In the next section you will be asked to construct more complicated functions which will make use of the MATLAB techniques covered in the earlier sections.

16

Examples of functions

Here are some exercises involving designing FMFs. Before you start this section, create a folder in your M-drive (Home Filestore) called MATH286. (recall section 7) To get to the top dircetory on your M-drive, type cd .. a few times until the Current Directory box shows M:\. Create a new (sub)folder in your MATH286 folder called PS1 Create a (sub)folder in this folder called testing. Remember that, in any directory, you can create a subfolder by right-clicking and selecting new/folder. So you should now have a directory (folder) path that looks like this: M:\MATH286\PS1\testing\ You will be using these folders for creating and testing the M-les. We will be using a similar structure for all the practical sessions (PS) and class tests (CT) from now on. This way you will be able to keep things organised and be able to nd them later.

25

16.1

Centre of gravity of point masses

The task here is to construct a function with the following specication: function [npoints M xbar ybar] = CoMass(x,y,mass) % CoMass.m % function [npoints xbar ybar] = CoMass(x,y,mass) % simple function to find centre of mass of system of point masses % system consists of all points in the first or third quadrant % % input: % x x coords % y y coords % mass vector of point masses % output: % npoints no. of points in first or third quadrant % M total mass of system % xbar x coord of CofM % ybar y coord of CofM % Draw yourself the xy-plane on a piece of paper. Draw in some (20 or so?) random points scattered all over the plane. Note which ones lie in either the rst (x > 0 and y > 0) or third (x < 0 and y < 0) quadrants. Count them. Now think about an algorithm to do what you have just done. Outline, on a piece of paper, the algorithm needed to loop over all points and test if x(i)*y(i) > 0. This means points where x and y are either both postitive or both negative. Outline how the total of such points is to be accumulated within this loop. This should be something like: set npoints=0 begin loop over points if x(i)*y(i) > 0 set npoints=npoints+1 end if end loop over points To get the total mass (M) of points at the same time one would modify this to be: set npoints=0, M=0 begin loop over points if x(i)*y(i) > 0 26

set npoints=npoints+1, set M=M+mass(i) end if end loop over points Now, the formulae for the coordinates of the centre of mass are x= 1 M xi m i ,
i

y=

1 M

yi m i ,
i

where M =
i

mi .

So we can include the calculation (sum) for these in a similar way: set npoints=0, M=0, xbar=0, ybar=0 begin loop over points if x(i)*y(i) > 0 set npoints=npoints+1, set M=M+mass(i) set xbar=xbar+x(i)*mass(i) set ybar=ybar+y(i)*mass(i) end if end loop over points set xbar=xbar/M, ybar=ybar/M Note the nal division by M to get the correct formulae for the coordinates. We are now in a position to translate this into MATLAB , using the syntax described in sections 11.1 (if) and 11.2 (loops). Go ahead and try this. Create the le CoMass.m, whose template is given above, in M:\MATH286\PS1\testing. Ask for help if you get stuck. Create the following main (driver) script (in M:\MATH286\PS1) to help run and debug your code: % Driver script for developing and testing CoMass.m % CoMdriver.m format compact path(./testing,path); clear all % CofM of system of point masses x=[0.7793 -0.7316 1.8009 -1.8622 -0.2450 1.0621 1.1808 -1.2525 -0.0409 -0.2177 0.8375 1.0187 -0.8959 0.7188]; y=[0.8659 -0.7283 1.8695 0.1970 -0.8956 2.2557 0.3009 0.7349 0.5223 -1.7535 -0.1745 -1.6171 2.0659 -1.8314 ]; m=[3 1 2 3 4 1 4 4 2 2 3 3 4 4]; plot(x,y,*) % plot all the points 27

-0.4738 ... 0.5853 ... 2.6340 ... -1.1925 ... 2 2 ...

grid % superimpose a grid on the plot [npoints M xbar ybar] = CoMass(x,y,m); % call the FMF disp( npoints M xbar ybar); disp([ npoints, M, xbar, ybar]); % show the results Note the use of the three dots ... to indicate that the line of code is continued on the next line. Note also the path command which tells MATLAB where to nd the FMF le CoMass.m. When you have debugged and run10 the le CoMass.m (by typing >> CMdriver while in PS1 as the current directory), you should nd that 7 of the points are in the specied quadrant and that their centre of mass is at the point (0.6382, 0.4373). What was their total mass? If you have successfully managed this, try adding in a test of the input vectors to check that they all have the same length. Use the error(message) command as in the quadsolve.m example of the last section. Remember to ask for help when you get stuck doing this. When you have run out of ideas you should be able to nd a correct solution CoMass.m on VITAL.

16.2

Centre of gravity of point masses in quadrants

The next example is a slight variation of the previous one. The specication is as follows: function [npoints M xbar ybar] = CoMassq(x,y,mass) % CoMassq.m % function [npoints xbar ybar] = CoMassq(x,y,mass) % finds centre of mass of systems of point masses % systems consist of all points in each quadrant % % input: % x x coords % y y coords % mass vector of point masses % output: % npoints no. of points in each quadrant (1:4) % M total mass of system (1:4) % xbar x coord of CofM (1:4) % ybar y coord of CofM (1:4) So, this time, the function is returning the results in vectors of length 4. There will be CoM coordinates for each quadrant as well as the total number points and their total mass in each case. The four quadrants are given by:
Note that when you execute CoMdriver.m you need to have M:\MATH286\PS1 as the current directory and the FMF CoMass.m should be in M:\MATH286\PS1\testing
10

28

1. x > 0 , 2. x < 0 , 3. x < 0 , 4. x > 0 ,

y>0 y>0 y<0 y<0

Note that, as in the last example, we have ignored points which fall on any axis as not, strictly speaking, being in a well-dened quadrant. We can modify the algorithm in section 16.1 along the following lines: set npoints=0, M=0, xbar=0, ybar=0 (for all 4 elements) begin loop over given points (length of vector) set q=0 (q will be quadrant number) if x(i) > 0 if y(i) > 0 set q=1 else set q=4 end this inner if else if y(i) > 0 set q=2 else set q=3 end this inner if end outer if if q>0 set npoints(q)=npoints(q)+1 set xbar(q)=xbar(q)+x(i)*mass(i) set ybar(q)=ybar(q)+y(i)*mass(i) set M(q)=M(q)+mass(i) end if end loop over points begin loop over quadrants if npoints(q) > 0 and M(q) > 0 set xbar(q)=xbar(q)/M(q), ybar(q)=ybar(q)/M(q) end this if end loop over quadrants The above algorithm description is not yet MATLAB code. In this state, it is sometimes referred to as pseudocode. Your next task is to translate it into MATLAB using the syntax you have learned so far. Some comments on how to do this: Create, by copying/pasting, a driving script CoMqdriver.m which will live in M:\MATH286\PS1: 29

% Driver script for developing and testing CoMassq.m % CoMqdriver.m % format compact path(./testing,path); clear all % CofM of system of point masses in all 4 quadrants x=[0.7793 -0.7316 1.8009 -1.8622 -0.2450 -0.4738 ... 1.0621 1.1808 -1.2525 -0.0409 0.0 0.5853 ... 0.8375 1.0187 -0.8959 0.7188]; y=[0.8659 -0.7283 1.8695 0.1970 -0.8956 2.6340 ... 2.2557 0.0 0.7349 0.5223 -1.7535 -1.1925 ... -0.1745 -1.6171 2.0659 -1.8314 ]; m=[3 1 2 3 4 1 4 4 2 2 ... 2 2 3 3 4 4]; plot(x,y,*) % plot all the points grid % superimpose a grid on the plot [npoints M xbar ybar] = CoMassq(x,y,m); % call the FMF disp( npoints M xbar ybar); disp([ npoints, M, xbar, ybar]); % show the results Now start a FMF CoMqMass.m in M:\MATH286\PS1\testing based on the function template given at the top of this section. Now copy in the above pseudocode and convert it en-block into comment lines.11 Work down the le converting it into correct MATLAB syntax. Other points to note Can use length(x) to nd how many points there are. Can use zeros(1,n) to initialise a row vector. Remember to use end to complete each if-else-end clause and also each for loop. Look back at the end of section 11.1 to see how to combine logical tests using the and operator. Remember to ask for help when you get stuck doing this. A correct solution will be on VITAL, but simply looking at this rst will not prepare you for having to code things for yourself in a Class Test. This is where you learn the ropes.
Note that you can convert a whole block of MATLAB le lines to/from comments by selecting (smearing) it with the mouse, right-clicking and choosing either Comment or Uncomment as appropriate.
11

30

16.3

System of forces

In this example we design and construct a function which, for a given system of n forces fi (i = 1, 2 . . . , n), nds the largest force, the total force and the angle between these. The n forces fi are stored as the columns of a MATLAB matrix F which therefore has 3 rows - the 3 components of each force. Here is the proposed specication: function [index maxmagF Fmax Ftot theta] = forces(F) % forces.m % function [index maxmagF Fmax Ftot theta] = forces(F) % given a system of forces F (3,:), % find the maximum and total forces and % the angle between these. % % input: % F matrix containing forces as columns % output: % index location of maximum force in F % maxmagF magnitude of maximum force % Fmax maximum force (col vector) % Ftot total force (col vector) % theta angle (in degrees) between Fmax and Ftot This le will go in M:\MATH286\PS1\testing. Here is a driver script ForcesDriver.m to help develop and test this. Copy and save it in M:\MATH286\PS1. % Driver script for developing and testing forces.m % ForcesDriver.m format compact path(./testing,path); clear all % system of forces % rand(state,12345); Fsystem=randi(10,[3,8])-5 [index maxF Fmax Ftot angle] = forces(Fsystem) Since there is a random number generator in this providing a random test matrix, the answers will be dierent every time it is run. If you want the calculation to be reproducible while doing early testing, uncomment the line % rand(state,12345); As usual, start by outlining the algorithm to be used. Note that since F is a matrix containing the forces as columns, the output variable index will be the column index of F corresponding to the force (column) whose magnitude (norm) is the greatest. A possible algorithm is 31

find no of rows (m) and cols (n) of F initialise (set to zero) index, maxmagF and Ftot loop i over number of forces (n) set Ftot = Ftot + force(i) set magF = norm of force(i) if magF > maxmagF replace maxmagF by magF set Fmax = force(i) set index = i end loop set costheta = (dot prod of Ftot and Fmax)/(maxmagF * norm(Ftot)) set theta = arccos(costheta) convert theta to degrees if necessary Some further hints: Use help acos to nd out about the inverse cosine. We get the angle between vectors a and b from a b = |a|b| cos() . Look back to section 8.7 to nd out about the magniitude of a vector. Look back at section 8.1 to see how to take a dot product of two vectors. As with the other examples, a correct solution will be on VITAL, but simply looking at this rst will not prepare you for having to code things for yourself in a Class Test.

16.4

Logistic map

Later in the module we will be coming across situations where some form of repeated caculation (iteration) is required in order to nd a solution. This example illustrates the idea of iteration until convergence using a simple loop with a convergence test. It is based on the so-called logistic map which provides a very elementary example of chaotic (e.g. turbulent) behaviour seen in many physical systems. The logistic map is x rx(1 x) where r is some parameter (> 0). The initial value of x is in the range 0 < x < 1. If the initial value is x0 , say, then the next value is x1 = rx0 (1 x0 ), then x2 = rx1 (1x1 ) and so on. Here is the function specication for a MATLAB FMF logmap.m which can do the iteration for us: 32

function [conv iters x] = logmap(r,xinit,maxiters,tol) % logmap.m % function [conv iters x] = logmap(r,xinit,maxiters,tol) % simple function for the first test % logistic map iteration % % input: % r logistic map parameter (r>0) % xinit initial value of x (0<x<1) % maxiter maximum number of iterations % tol tolerance on convergence % output: % conv 1 if converged, 0 if not % iters number of iterations % x vector of iteration values 1,2...iters This le will go in M:\MATH286\PS1\testing. Here is a suitable driver script LogmapDriver.m which you should put in M:\MATH286\PS1: % logmap driver script for developing and initial testing % LogmapDriver.m r=1.5; x0=0.99; maxit=1000; tol=0.0001; [conv iters x] = logmap(r,x0,maxit,tol); its=0:iters; plot(its,[x0 x]) conv iters Next, sketch out an algorithm to deal with the above FMF specication. Within the iteration loop, we will use x0 to denote the current value of x and x1 to denote the next value given by the map formula. Thus at the rst pass through the loop, x0 will be input argument xinit which is used to calculate x1. Before going round the loop a second time, we need to set x0 to the value of x1, and so on. Since we want to return all the values of xi calculated in the iteration (as a MATLAB vector), we need to keep extending this vector as the values are calculated (see section 8.5). intialise x0, conv, and the vector x begin loop over iters set x1 = r*x*(1-x) extend vector x with x1 set delta = abs(x1-x0) set x0=x1 if delta <= tol conv =1 (it has converged) 33

break out of the loop end of this test end loop over iters Some notes on this: Recall that x=[ ] establishes x as an empty vector. The MATLAB command break stops the exucution in a loop and restarts execution at the rst line after the loop. The vector x contains only the calculated values xi (i = 1, 2, . . . iters). The plot command in LogmapDriver.m adds in the initial value x0 before plotting them. Do your best to translate this into MATLAB and to debug it before resorting to downloading the solution from VITAL. If you have time to play with it (using dierent values of the parameter r and the starting points x0 ), you might want to see if you can reproduce the following expected behaviour: 0<r1 x0 1<r<2 x (r 1)/r 2<r<3 as above but with large uctuations oscillations about X1 (r) and X2 (r) 3 < r < + 6 1 r > 1 + 6 3.45 complicated, chaotic for r > 3.57 Here x 0 means the x-values tend to 0 irrespective of the the starting point x0 . Check this by looking at your plot. The values X1 (r) and X2 (r) are two values which the iteration ips between. The numerical values depend on r. Again, you can check this by looking at your plots. Try using the zoom tool from the Tools menu in the plot (Figure 1) window. (Look at doc zoom for more details.

17

What happens next?

The idea is that when you have worked through sections 1 to 15, you should try the MCQ test on VITAL. At that point, you should also have started working through section 16. Only when you have passed the MCQ test will you be able to take Class Test 1. This will be an exercise similar in standard to one of the above examples. More details about this will be given in the lectures. In order to prepare you for Class Test 1, we have provided a mock class test called Class Test 0, which does not contribute to your marks in any way. It is based on the example in section 16.3. A separate set of notes about this (ct0notes.pdf) are provided on VITAL. ACI noteswk1-4.tex, ver 1.11 18/10/2011 34

Вам также может понравиться