You are on page 1of 9

SESG1009: Assignment 1

Getting started
Log on to the computer using your login and password. (If you have not yet got a username then click on the subscribe icon to register!) Remember, that when you log out (at the end of this lab), all les that you have created on the local hard-drive (C:) will be deleted! The good news is that you are automatically connected to your personal lestore (this is usually mapped to drive H:\ and called My Documents. Remember: in order to avoid losing your les, save everything to your lestore, i.e. save it into H:\. Save your work frequently, because Matlab, MS Excel, or whatever program you are using (or the operating system) might crash and you will lose your work. You might accidentally delete or break something in your les. In that case, just go back to the last version you have saved. Should you get stuck, try to solve the problem: it is important to test dierent approaches one of them might achieve want you want to do! Also, try the online help, be creative! (Of course, you can ask a demonstrator for help.) Write answers to questions in your log book the demonstrator will use this to mark your work. (We use this symbol log book to remind you.) Dont forget to save all your work (save it to your lestore, not to the local hard disk) as you will have to show it to a demonstrator for marking at the end of this session or in the beginning of the next lab-session. Before you ask a demonstrator to mark your work, send an email to sesg1009@soton.ac.uk. Attach all your electronic work (i.e. the les you have created) to this email. Make sure the lenames of the attached les agree with the le names given in the instructions on the following pages. You will get a receipt of your submission (via email). Read the receipt to check that your submission went well, and keep it to show it to the demonstrator before marking. To start MATLAB , click on Start, All Programs, Numerical Modelling, Matlab, Matlab for Teaching. Some questions are marked as Tricky. You will have to solve these (at least partly) to get all the points, but dont worry if you cant you should still be able to get a good mark by answering everything else.

Preparing your lestore


Using Windows Explorer (the default le manager for the Windows operating system), create a new folder for this module in your home lestore on drive H:\. Then you can create a new sub-folder for each lab session, for example: H:\sesg1009\lab1 If you require help with this, please ask the person next to you or a demonstrator. We suggest that you create a directory for SESG1009 on H: and then have one subdirectory for each laboratory session. For example, save all les for laboratory session 1 into H:\sesg1009\lab1. (This will keep your le store organised. You can later add new subdirectories such as H:\sesg1009\lab2, H:\sesg1009\lab3 . . . for the following sessions).

How to get help . . . ?


Raise your hand to attract the attention of a demonstrator who can then help with your query, provide advice and give feedback. In MATLAB , use Matlabs help command, for example type >> help sqrt at the Matlab command prompt (>>). A whole length of text will then be displayed for the specic command (here: sqrt). If you are interested in more details for Matlab-specic functions and operations, you can type helpdesk at the Matlab Command prompt and thus call up Matlabs help documentation system.

Matlab hint
Recalling previous commands When you are on the Matlab command line prompt (>>) and want to re-use a previous command that you typed, you can press the up arrow key, , to cycle through previous commands (or use MATLABs History window).

Before you start . . .


PC self-test We provide a number of links to brief self-test questions on the modules web page: http://www.soton.ac.uk/~sesg1009. These will help you to self-assess your level of knowledge for these exercises and provide immediate feedback to you. Try them out either in the rst 5 minutes of the labs or in your spare time or in the surgery session.

First steps with MATLAB : simple calculations

Exercise 1. (5 points)
To keep track of your work, create three columns in your log book as shown in the table below. For each mathematical expression shown below, compute the answer and write down the way you have to express the command for MATLAB to evaluate it. As an example, we have included the answer to the rst question: log book formula 24 1 . . . Compute Compute Compute Compute Compute Compute Compute Compute MATLAB syntax result 2^4 16 sqrt(1) 1.0 . . . . . . 78 10 + 10 20 2 2 3.5 1010 sin(32 ) sin2 (3) cos() sin()

Tricky: Is this what you expect? Can you explain this? ( log book) Compute cos2 (0.9) + sin2 (0.9)

Tricky: Is this result surprising? Why (not)? ( log book) Compute tan(/2)

Tricky: Is this result surprising? Why (not)? ( log book)

Arrays (one-dimensional) and the colon-operator

Exercise 2. (5 points)
Type in the following commands, and write down for each line what it achieves ( log book). Try to describe what happens rather than what is printed on the screen (this requires some thought). Here are some examples:
Command help pi s=5 s=5; A good comment (full marks) shows the help page for pi or shows the denition of pi assigns the value 5 to variable s the semicolon suppresses printing of the value of s Not a useful comment (no marks) PI 3.1415926535897.... PI = 4*atan(1) = imag(log(-1)) = 3.1415926535897.... >> s = 5 nothing

Here starts your exercise: (You should not waste time typing in the comments following the %-sign.) log book
a = 1:5 b = 10:10:50 b(4) b(1:3) b([1,2,5]) c = a peter d = a e = a f g h h = = = = + b = a - b .* b ./ b

% Dont worry about the dot at the moment: we will understand later why we need it. % However, do describe what .* and ./ achieve.

sqrt(a) a .^0.5 a * 10 a + 42 % This shows the les in the current directory. % You can change your current directory using the cd-command. % Try cd h:\ to go to your home lestore and back.

dir

save my_vars whos clear whos load my_vars whos D = dot(a(1:3), b(1:3) ) C = cross(a(1:3), b(1:3) ) t = 0:0.1:1 t_rev= 1:-0.1:0 % tricky % tricky

A rst look at m-les and the plot command

MATLAB provides a convenient way to summarise a sequence of commands in a le which can then be executed by typing the name of the le on the MATLAB prompt. Lets work through an example: 1. Check what is MATLABs current working directory by typing
>> pwd % PWD stands for Print Working Directory

If this is not your lestore (which should be connected to h\:), then change it by typing
>> cd h:\

You can use pwd again to convince yourself that this has worked. Remember that you can use dir to look at the les in the current directory. (If you follow our suggestions given earlier in this document, then change the working directory to h:\sesg1009\lab1 by typing cd h:\sesg1009\lab1.) 2. On the MATLAB prompt, type edit my script.m 3. MATLAB will create a le for you, which is called my script.m. Note the .mending of the le name: this is the convention for naming MATLABs les. A window that allows you to edit your le my script.m should appear. 4. In this editor, you can now enter MATLAB commands in the same way as you would use the MATLAB command prompt. However, the commands you type will not be executed straight away but only when the whole script-le is executed. 5. As an example, lets write a script to plot the (un-normalised) Gaussian distribution. Type the following commands in the editor (including the rst line, which is a comment):
% This is my first m-script. It plots the Gaussian distribution. disp(Starting the script) x=-5:0.1:5; y=exp(-x.^2); plot(x,y); disp(finished plotting the Gaussian distribution)

6. Now save your script by clicking on File and then Save. Save your le with lename my script.m in the subdirectory that you created earlier, H:\sesg1009\lab1. 7. Go to the MATLAB prompt, and type
>> my_script

8. Now the commands in your script are executed (line by line) you should see the plot popping up in a gure window. (Should this fail, then verify using pwd and dir that the le my script.m is stored in the correct place.) 9. Type
>> help my_script

You should nd that MATLAB picks the rst block of comment lines (starting with %) in your m-le, and displays the comments. This is an excellent way of documenting your scripts: in case you have forgotten what they do, you just use the help-command, as you would for built-in MATLAB commands.

Plotting graphs
You have just used a simple form of the plot command to draw the Gaussian distribution on a xy-coordinate system. Let us nd out how to use it to plot sin(t) and cos(t) for t ranging from 0 to 2. Try to understand the following commands and what they do when you type them at the Matlab command prompt:
time = 0:0.1:2*pi; my_sin_wave = sin( time ); my_cos_wave = cos( time ); plot(time,my_sin_wave); plot(time,my_cos_wave); plot(time,my_cos_wave,o); plot(time,my_cos_wave,-); % note the semicolon at the end!

% to draw both, points and lines, use help plot % to gure it out! % whats going on now?

plot(my_sin_wave, time);

plot(time,my_sin_wave,r) % Okay, lets plot sin and cos! hold on % now we can add more plot-commands to draw in our chart! plot(time,my_cos_wave,g) xlabel(time) ylabel(Function value) title(My first cos and sin graphs in MatLab!) legend(sin(t),cos(t)) hold off % Done! plot(my_sin_wave, my_cos_wave) % Tricky: can you gure out what happens here?

Exercise 3. (10 points)


Now that you know how to use m-les and how to create simple plots, let us combine the plotting commands in a .m le to plot the functions exp(t) and t2 together in one chart with t ranging from 0.0 to 2.0, in steps of 0.05. We want the exp-function to be displayed as a blue line, and the t2 function as red circles. Create a new m-le with name plot functions.m that will contain the commands to create the plot for this exercise. Choose and enter a sensible comment block for your m-le, and check that it works by typing
>> help plot functions

Your comment should include: name of the le short summary of the purpose of this le your name and email the current date Here is an example of a good comment (which is extending over 6 lines) for a small program that prints Hello Universe:
% % % % % % hello.m This program is greeting the universe (just an example for SESG1009) Marc Molinari, mm2@soton.ac.uk, 20/01/2008

fprintf(Hello Universe! \n);

Please remember that it is very important to add such a comment block to all your future .m or other program source les! After the comment block, enter the required Matlab commands to perform the following tasks (you can use the previous code as an example) Create a vector t with values ranging from 0.0 to 2.0 in steps of 0.05. Plot the two functions exp(t) and t2 together in one graph. Draw the exp function as a blue line, and the t2 function red with circles. Do not forget to label your graph appropriately (title, x-axis, y-axis, legend). Save the code in the le plot functions.m in your SESG1009 lab1 subdirectory. You can also save the gure if you wish to do so: in the gure window click on File, then on Save As. . . . Then try to save your gure in standard JPG format. When you have nished, write a brief summary of all the new commands from section 3 into your logbook. log book 7

A rst look at for-loops

You need a new command for this exercise: the disp(x)-command will display just the value of x, but not the name of the variable. Example:
>> x = 10.3; >> disp(x) 10.3000 >>

Note that you can also print strings, for example:


>> disp(this is line 33) this is line 33

Exercise 4. (10 points)


Create a new m-le with name forloop.m and type in the following commands:
for i = 1:10 a = 3*i; disp(a) disp(Hello World) end

Run your program and try to understand what it does. You can add more commands (for example disp(i);) or modify the program as you like to help you understand what it does. Write down (for every line) what is achieved ( log book).
(Once you have understood what the for-loop does, you can remove the Hello World print statement we have only inserted it to help you understand the iterative nature of the loop.)

Save the above program as forloop squares.m and modify it such that it computes and prints the numbers 12 , 22 , 32 . . . 102 . Dont forget to click save once you have modied it. Create a new program with lename forloop sum.m by copying these lines:
s = 0; for i = 1:10 s = s + i; end disp(s)

Run the program and try to understand what it does. Write a short description of this program into your log book. log book Hint: Maybe you need to add another disp(s); or disp(i); somewhere to understand what is happening. Create a new le called forloop product.m and write the code to compute the product 1*2*3*4*5*6*7*8*9*10. 8

Tricky: Can you think of a method to compute the sum of squares between 1 and 10, as in 12 + 22 + 32 + . . . + 102 = k=10 k 2 ? Save this as forloop sumsquares.m k=1 or write the code in your log book.

. . . when you have nished


When you have nished and saved all your work: First, make sure you can see the le extensions in Windows Explorer. Open a new Explorer window either from the Start button or by pressing the key-combination Windows + E. In Explorer, open the menu labelled Tools, then select Folder options. Then go to tab View and under Advanced Settings uncheck the entry Hide extensions for known le types. Then click on Apply to All Folders. This will ensure that you can now see the extension of your les (.doc, .m, .pdf, ...) in Explorer. Send an email with your work to sesg1009@soton.ac.uk: Use lab 1 as the subject line (without the quotes). Attach all your electronic work to the email. For this assignment attach the m-les my script.m and plot functions.m from exercise 3, and the m-les forloop squares.m, forloop sum.m, forloop product.m, and forloop sumsquares.m from exercise 4. You should receive an electronic receipt of your submission (via email) within a few minutes. Check that all les have been received (the receipt will tell you if the system didnt recognise any les). Then nd a demonstrator and get your work marked. (Keep the email receipt to show it to the demonstrator.) If you need to complete the assignment outside the lab-session, then you have to have it nished before your next laboratory session starts so that you can get it marked in the beginning of your next session (not later!). Make use of the weekly help sessions (surgery).

Id: lab1.tex 449 2010-01-25 20:34:53Z mm

You might also like