|Starting up Matlab||Exercise 2|
|Using a browser to download files||Exercise 3|
|Getting help||Exercise 4|
|Lab summaries||Exercise 6|
|More on Matlab||Exercise 7|
|Matlab files||Exercise 8|
|Variables and values||Exercise 9|
|Variables are Matrices||Exercise 10|
|Vector Operations||Exercise 11|
|Ordinary differential equations and graphics|
This lab will occupy three lab sessions. The first session will introduce the mechanics of using Matlab on the Linux PCs here in the lab. There is some reading to be completed before the second session and you can do that here in the lab or at any other computer with web access. The following two sessions will present exercises in Matlab use.
The discussion that follows assumes that you are basically familiar with using a Unix-like operating systems such as Linux, browsing the Web, and, to a lesser extent, using telnet (or ssh) to log in to campus computers. The next few paragraphs will give a brief introduction to Matlab and explain how to use it and those aspects of the environment that will be important to doing the labs.
The labs roughly follow the material presented in lecture, but are independent of the homework and other exercises presented in lecture. Lab grades count as 30% of your course grade.
Attendance is not required, but help is most readily available during the lab sessions.
You are encouraged to work together with other students, but you are expected to provide your own diary and summary files (explained further below).
Each lab will be given a grade of A+, A, B, or 0. These grades correspond with percentage grades of 99, 94, 88, and 0. At the end of the semester, your grades will be averaged and then integrated with your grade in lecture. A student who achieves an A+ on each of the labs will be given an overall grade of 100 rather than 99. The grading criterion is:
Each lab is due before the beginning of the next lab. Labs submitted after the day the following lab begins will have 1% deducted from the grade. An additional percent will be deducted for each further week they are late. The final due date for labs 2 through 6 is the last day of classes for the semester, and the final due date for labs 7 through 10 will be announced near the end of the semester. Labs that are not submitted before the final due date will be given a grade of zero.
In this section you will see how to start up recent versions of Matlab that use the Java windowing interface. These instructions are the same for the Unix and MS-Windows versions of Matlab. I will also give the command-line equivalents of many of the commands. These command-line equivalents are valid for all versions of Matlab, and many of them are valid for the Matlab clone named Octave. Generally speaking, anything you can do using a menu can also be done with command-line equivalents. You would use the equivalents when writing scripts and the menus when working interactively.
Sometimes, the window will open up containing a large number of warning messages about files missing. These messages are ``normal'' and can be safely ignored.
The default window is divided into a larger pane on the right, and two panes, each with identification tabs at the bottoms, on the left. The right windowpane is a command windowpane and you will be typing Matlab commands in it. On the left side of this command windowpane somewhere (near the bottom in the figure) there will be a prompt of the form ». Your typed commands go next to this prompt.
There are two choices for display on each of the two windowpanes on the left. I suggest that you choose ``Workspace'' on the top and ``Command History'' on the bottom in general, although we will have occasion to use ``Current Directory'' on the bottom.
If you wish to use the command line to create and switch directories, you can switch to your permanent ``AFS/private'' directory with the ``change directory'' commands
cd Desktop cd AFS cd privateYou create a directory named math2071 with the commands
mkdir math2071and you can make it the current directory with the command
cd math2071You can always find the name of your current directory with the command
pwdand you can get a listing of the files in the current directory with either the command
diror the command
Before going on, create the directory math2071, with subdirectories lab01, lab02, ..., lab10.
diary diary.txtThe name diary.txt is actually the name of the file that is created and you can use any name you like. It is a text file, and you should use .txt to name it. Before going on, type this command in the ``Command'' windowpane. Terminate the command by hitting the ``Enter'' key.
You should also type a comment line that will help you identify your work later. It should start with the comment character, a percent sign %, and include the lab number and date. This line will serve as an identifier when you look at the file.
!zip labfiles.zip *.m *.jpg *.txtwhere ``labfiles.zip'' is the name of the file and can be chosen as you wish. (The exclamation point is necessary to tell Matlab that the command is a ``system'' command and not a Matlab command.) You then only need to attach this one file to your email. You should do this only once, when you have completed all your work.
The storage in your AFS area is quite limited, amounting only to eight megabytes or so. This is plenty for the work we are doing, but if you try to keep many old files or files from other courses there, you will run out of space. The computers in GSCC support using USB drives (``thumb'' drives or ``jump'' drives) to save your files. You can insert a USB drive into one of the USB slots and wait a few seconds. A new icon will show up on the desktop and you can double-click on it to see the contents of the drive. You can drag and drop files from other directories into your USB drive directory, thus making portable copies of your files.
It is important to realize that you must not simply remove the USB drive from its slot! Instead, when you are ready, go to the icon on the Desktop representing your USB drive and right-click on it. Choose ``unmount'' or ``eject'' on the menu and give it a little time to get its act together. Then you may remove the drive. The reason for this rigmarole is that data does not get written immediately to the drive, but is written at the computer's leisure. Unmounting the drive forces the last data to be written. You may have noticed that MS-Windows offers the option to ``safely remove'' a USB drive, which accomplishes the same thing.
Some of the labs require that you download files from the web in order to use them. The following exercise illustrates how to download files. The file you will download is a very simple script file.
Right-mouse click on the file demoscript.m
to bring up a menu. Choose ``Save link as'' and a file save
box will pop up. Navigate to the directory you made:
and save the file with the name demoscript.m. You must use
the .m extension to tell Matlab that the file contains Matlab
commands. Return to the Matlab command window. The file should be
visible to Matlab, a fact that you can confirm with the dir
command or by its presence in the ``Current Directory'' windowpane.
Edit the file by typing the command
edit demoscript.mor by double-clicking on the file in the ``Current Directory'' windowpane, or using the ``FileOpen'' menu pick. An edit window will show up. Read through the file: the comments make it self-explanitory.
You can tell Matlab to execute the file by typing its name, without the ``.m'', on the command line, or by choosing ``Run'' from the Debug menu on the edit window. (The final statements in the file and comments refer to the following exercise.)
The following two exercises illustrate the use of the debugging capability of Matlab. Most of the time you will be able to see what is wrong from the Matlab error messages, but sometimes the error is not obvious. In Exercise 2 below, you will see what you might do when you just cannot see why something is wrong.
dbstop if error dbstop if naninfor through the Breakpoints menu on the Edit window.
dbquitThis action will return Matlab to its usual » prompt.
dbclear allor from the debugging menu in the edit window.
The following exercise illustrates how you can use the debugger to trace execution. It uses the same demoscript.m file as before.
It is important to be able to get help when you need it. Matlab provides two help facilities from inside Matlab itself and a third on the web. The easiest way to get help is to use the ``Help'' menu at the top of the Matlab window. Command-line help is also available from the Matlab prompt by typing ``help command''. For example,
help diaryYou will get a short description of how to use the command. You will also get a list of related commands near the bottom of the help description, and you will often find other appropriate commands there. When you write your own Matlab macro files, you should always include some special comments in the beginning of the file. The comments up to the first executable statement or blank line will be printed out in response to the help command. For example, the command
help demoscriptwill give a quick help message from the first three lines of demoscript.m. You may notice that the first of these lines is included in the file listing in the ``Current Directory'' windowpane.
A second way to get help from the command prompt is the following.
helpdeskThis command brings up a comprehensive help facility, the same one that the Help menu brings up. This help facility is very similar to the one on the web from the URL:
You exit Matlab by typing quit at the command line or by using the FileExit menu choice.
You should complete a report of the results you obtained for each completed lab. This report need not be elaborate. The report consists of at least two files: the original diary.txt file(s) plus a summary file. This summary file can be easily created as you do the lab by keeping a text file up in the editor and copying parts of the web page, your commands and output to the file as you work. Another way is to start from the diary.txt file and delete all your false starts and errors to produce a compact record. Click here to see a sample summary file.
This summary file is very important. It is what I will read first and, if it is well-written and the work is done correctly, I will not need to read anything else. Never put incorrect Matlab statements into your summary because it will take me a lot of time to discover you really didn't mean them. I expect to see
Summarizing your work is important not only for my convenience in this class but also for your own research work. In your research, you may be running very many different Matlab sessions and you will not remember from month to month what each one did. The idea of the summary is that you can easily refresh your memory on exactly what you did to accomplish some particular task.
Here is what I want to see in the summary file:
If you want to know how much detail to include, think of the following scenario. You have completed this course and, a year from now, a friend who is taking the course is having trouble. Your friend comes to you and asks how you did a particular exercise. You have saved your work, so you go look at it. The first place you will look is in your summary to see what you did. If the summary file contains only ``Exercise 1.a: complete,'' you will then have to go re-read the original lab and look for your script files, etc. The objective of the summary is that you can read what you did and then explain it in general to your friend without referring to other materials. If your friend needs more detail, you can look at the other files you wrote for the lab.
Do not write a summary of the work in this lab so far. Instead, please read the following information about Matlab commands from either the PC here in the lab or from another computer on the web.
The Mathworks, maker of Matlab, includes a short tutorial on using Matlab called Getting Started This tutorial is also available from the Matlab command prompt with the command helpdesk and also from the Help menu, and, if you have your own copy of the Matlab manuals, it comprises the ``Getting Started'' book.
The beginning of the ``Getting Started'' tutorial is the best presentation of the general capabilities of Matlab that I have come across. In order to have an overview of Matlab, browse through the first sections of the tutorial. There are only the equivalent of about 35 pages of material here, mostly very easy to understand. The two most important chapters are Desktop Tools that covers use of the Matlab windows, and Manipulating Matrices that covers use of Matlab as a tool for mathematics.
Begin this tutorial now, during your first lab session. Read as much of it as you can now, and complete it at home or from any convenient computer connected to the web. The list of topics that follows (roughly in order of appearance) are topics that will be necessary for this semester's labs. The sections following this one will address some of these topics, but you will be well-served if you have seen the introduction.
The following sections discuss more of the use of Matlab. I will expect a summary of your work for the rest of this lab.
The best way to use Matlab is to use its scripting facility. With sequences of Matlab commands contained in files, it is easy to see what calculations were done to produce a certain result, and it is easy to show that the correct values were used in producing a graph. It is terribly embarrassing to produce a very nice plot that you show to your advisor only to discover later that you cannot reproduce it or anything like it for similar conditions or parameters. When the commands are in clear text files, with easily read, well-commented code, you have a very good idea of how a particular result was obtained. And you will be able to reproduce it and similar calculations as often as you please.
The Matlab comment character is a percent sign (%). That is, lines starting with % are not read as Matlab commands and can contain any text. Similarly, any text on a line after a % can contain textual comments and not Matlab commands.
A Matlab script file is a text file with the extension .m. Matlab script files should always start off with comments that identify the author, the date, and a brief description of the intent of the calculation that the file performs. Matlab script files are invoked by typing their names at the Matlab command line or by using their names inside another Matlab file.
Matlab function files are also text files with the extension .m, but the first non-comment line must start with the word function and be of the form
The key difference between function and script files is that functions are intended to be used repetitively. They can accept parameters and variables used inside a function are invisible outside the function. When I am working on a task, I often start out using script files. As I discover just what tasks are repetitive or when I start to need the same calculation repeated for different parameters, or when I have many intermediate variables that might have the same names as variables in other parts of the calculation, I switch to function files. In these labs, I will specify function file or script file when it is important, and you are free to use what you like when I do not specify.
Because function files are intended to be used multiple times, it is a bad idea to have them print or plot things. Imagine what happens if you have a function that prints just one line of information that you think might be useful, and you put it into a loop that is executed a thousand times. Do you plan to read those lines?
Matlab commands are sometimes terminated with a semicolon (;) and sometimes not. The difference is that the result of a calculation is printed to the screen when there is no semicolon but no printing is done when there is a semicolon. It is a good idea to put semicolons at the ends of all calculational lines in a function file.
Matlab also supports data files. The Matlab save command will cause every variable that Matlab currently knows about to be saved in a file called ``matlab.mat''. You can also name the file with the command save filename that will put everything into a file named ``filename.mat''. This command has many other options, and you can find more about it using the help facility. The inverse of the save command is load.
Note: Matlab function names are case-sensitive. This means that the function cos is different from Cos, coS, and COS. File names in Unix and Linux are also case-sensitive, but file names in MS-Windows may not be. In order that no confusion arises, all file names and all function names in this course will be lower-case.
Values in Matlab are always ``floating point'' numbers with about sixteen decimal digits of accuracy. When Matlab prints values, however, it will truncate a number to about four digits to the right of the decimal point, or less if appropriate. Values that are integers are usually printed without a decimal point. Remember, however, that when Matlab prints a number, it may not be telling you all it knows about that number.
When Matlab prints values, it often uses a notation similar to scientific notation, but written without the exponent. For example, Avogadro's number is in usual scientific notation, but Matlab would write this as 6.022e+23. The e denotes . Similarly, Matlab would write 1/2048=4.8828e-04. You can change the number of digits displayed with the format command. (See help format for details.)
Matlab uses variable names to represent data. A variable name represents a matrix containing complex double-precision data. Of course, if you simply tell Matlab x=1, Matlab will understand that you mean a matrix and it is smart enough to print x out without its decimal and imaginary parts, but make no mistake: they are there. And x can just as easily turn into a matrix.
A variable can represent some important value in a program, or it can represent some sort of dummy or temporary value. Important quantities should be given names longer than a few letters, and the names should indicate the meaning of the quantity. For example, if you were using Matlab to generate a matrix containing a table of squares of numbers, you might name the table tableOfSquares. (The rule I am using here is that the first part of the variable name should be a noun and it should be lower case. Modifying words follow with upper case letters separating the words. This rule comes from the officially recommended naming of Java variables.)
Once you have used a variable name, it is bad practice to re-use it to mean something else. It is sometimes necessary to do so, however, and the statement
clear firstVariable secondVariableshould be used to clear the two variables firstVariable and secondVariable. This same command is important if you re-use a variable name but intend it to have smaller dimensions.
Matlab has a few reserved variable names. You should not use these variables in your m-files. If you do use variables such as i, they will lose their special meaning until you clear them. Reserved names include
We said that Matlab treats all its variables as though they were matrices. Important subclasses of matrices include row vectors (matrices with a single row and possibly several columns) and column vectors (matrices with a single column and possibly several rows). One important thing to remember is that you don't have to declare the size of your variable; Matlab decides how big the variable is when you try to put a value in it. The easiest way to define a row vector is to list its values inside of square brackets, and separated by spaces or commas:
rowVector = [ 0, 1, 3, 6, 10 ]The easiest way to define a column vector is to list its values inside of square brackets, separated by semicolons or line breaks.
columnVector1 = [ 0; 1; 3; 6; 10 ] columnVector2 = [ 0 1 9 36 100 ](It is not necessary to line the entries up as I have done, but it makes it look nicer.)
Matlab has a special notation for generating a set of equally spaced values, which can be useful for plotting and other tasks. The format is:
start : increment : finishor
start : finishin which case the increment is understood to be 1. Both of these expressions result in row vectors. So we could define all the integers between 10 and 20 by:
integers = 10 : 20and just the even values from 10 to 20 by:
evens = 10 : 2 : 20
Sometimes, you'd prefer to specify the number of items in the list, rather than their spacing. In that case, you can use the linspace function, which has the form
linspace( firstValue, lastValue, numberOfValues )in which case we could generate fifty numbers with the command:
x = linspace ( 10, 20, 50 )As a general rule, use the colon notation when the increment is an integer or when you know what the increment is and use linspace when you know the number of values but not the increment.
Another nice thing about Matlab vector variables is that they are flexible. If you decide you want to add another entry to a vector, it's very easy to do so. To add the value 22 to the end of our evens vector:
evens = [ evens, 22 ]and you could just as easily have inserted a value before the other entries, as well.
Even though the number of elements in a vector can change, Matlab always knows how many there are. You can request this value at any time by using the length function. For instance,
length ( evens )should yield the value 7 (the 6 original values of 10, 12, ... 20, plus the value 22 tacked on later). You can also view the length of vectors by looking in the Workspace windowpane. In the case of matrices with more than one nontrivial dimension, the length function returns the total number of entries. Use the size function in this case. For example, since evens is a row vector, size( evens )=[1 7], size( evens, 1)=1 and size( evens, 2)=7.
To specify an individual entry, you need to use index notation, which uses round parentheses enclosing the index of an entry. The first element of an array has index 1 (as in Fortran, but not C and Java). Thus, if I want to alter the third element of evens, I could say
x(3) = 7
plot(meshPoints, sin(2*pi*meshPoints))Please save (export) this plot as a jpeg (.jpg) file and include it with your summary.
% Lab 1, exercise 5 % A sample script file. % Your name and the dateFollow the header comments with the commands containing exactly the commands you used in the earlier parts of this exercise. Test your script by using clear to clear your results and then execute the script from the command line by typing exer5, by using the ``Run'' button (looks like a sheet of paper with an arrow pointing down) at the top of the edit window, or by using DebugRun from the edit window menus.
Matlab provides a large assembly of tools for matrix and vector manipulation. We will investigate a few of these by trying them out.
rowVec1 = [ -1 -4 -9] colVec1 = [ 2 4 -8 ] mat1 = [ 1 3 5 7 9 2 4 6 8 ]
colVec2 = (pi/4) * colVec1
colVec2 = cos( colVec2 )Note that the values of colVec2 have been overwritten. Are these the values you expect?
colVec3 = colVec1 + 2 * colVec2
illegal = colVec1 + rowVec1;Look carefully at the error message. You must recognize from the message what went wrong when you see it in the future. Unfortunately, Matlab error messages are not always clear.
colvec4 = mat1 * colVec1
mat1Transpose = mat1' rowVec1 = colVec3'Warning: The single quote really means the complex-conjugate transpose (or Hermitian adjoint). If you want a true transpose applied to a complex matrix you must use ``.'''.
mat2 = mat1 * mat1' % mat2 is symmetric rowVec2 = rowVec1 * mat1 dotProduct = colVec3' * colVec1 euclideanNorm = sqrt( colVec2' * colVec2 )
determinant = det( mat1 ) traceOfMat1 = trace( mat1 )
A=magic(100); % please do not print all 10,000 entries.then the largest and smallest row sums, the largest and smallest column sums, and the sums of the two diagonals are all the same, and hence that all row, column and diagonal sums are equal to each other.
integers = 0 : 10but now we'll get an error when we try to multiply the entries of integers by themselves.
squareIntegers = integers * integers
Realize that Matlab deals with vectors, and the default multiplication operation with vectors is row by column vector multiplication. In order to do element-by-element multiplication, we need to place a period in front of the operator:
squareIntegers = integers .* integers
Now we can define cubeIntegers and fourthIntegers in a similar way.
cubeIntegers = squareIntegers .* integers fourthIntegers = squareIntegers .* squareIntegers
Finally, we would like to print them out as a table. integers, squareIntegers and cubeIntegers are row vectors, so make a matrix whose columns consist of these vectors and allow Matlab to print out the whole matrix at once.
tableOfPowers= ... [integers', squareIntegers', cubeIntegers', fourthIntegers']
squareIntegers = integers .^ 2These problems never come up with addition or subtraction; nor do they occur with division or multiplication by a scalar.
squaresPlus1 = squareIntegers + 1
cubeIntegers ./ squaresPlus1 cubeIntegers / squaresPlus1
tableOfCubes = tableOfPowers(:,[1,3]) tableOfOddCubes = tableOfPowers(2:2:end,[1,3]) tableOfEvenFourths = tableOfPowers(1:2:end,1:3:4)
A = magic(10)What commands would be needed to generate the four matrices in the upper left quarter, the upper right quarter, the lower left quarter, and the lower right quarter of A?
It is critical to be able to ask questions and to perform repetitive calculations in m-files. These topics are examples of ``flow control'' constructs in programming languages. Matlab provides two basic looping (repetition) constructs: for and while, and the if construct for asking questions. These statements each surround several Matlab statements with for, while or if at the top and end at the bottom.
Note: It is an excellent idea to indent the statements between the for, while, or if lines and the end line. This indentation strategy makes code immensely more readable. Your m-files will be expected to follow this convention.
The syntax of a for loop is
|for control-variable=start : increment : end|
|Matlab statement ...|
The syntax of a while loop is
|Matlab statement initializing a control variable|
|while logical condition involving the control variable|
|Matlab statement ...|
|Matlab statement changing the control variable|
The syntax of a simple if statement is
|if logical condition|
|Matlab statement ...|
The syntax of a compound if statement is
|if logical condition|
|Matlab statement ...|
|elseif logical condition|
Note that elseif is one word! Using two words else if changes the statement into two nested if statements with possibly a very different meaning, and a different number of end statements.
% find the infinity norm of a vector v N=length(v); norm=abs(v(1)); for n=2:N if abs(v(n))>norm norm=abs(v(n)); % largest value up to now end end norm % no semicolon means value is printed
v=[ -5 2 0 6 8 -1 -3 -10 ];
If you have to type everything at the command line, you will not get very far. You need some sort of scripting capability to save the trouble of typing, to make editing easier, and to provide a record of what you have done. You also need the capability of making functions or your scripts will become too long to maintain. In this section we will consider first script files and later function m-files.
v = [-35 -20 38 49 4 -42 -9 0 -44 -34];
% find the two norm of a vector v N=length(v); norm=v(1)^2; for n=2:N norm = norm + v(n)^2; end norm=sqrt(norm) % no semicolon means value is printed
Script files are very convenient, but they have drawbacks. For example, if you had two different vectors, v and w, for which you wanted norms, it would be inconvenient to use exer8a or exer8b. It would be especially inconvenient if you wanted to get, for example, . The solution to this inconvenience is to use function m-files. Function m-files define your own functions that can be used just like Matlab functions such as sin(x), etc.
function norm=infinityNorm(v) % norm=infinityNorm(v) % v is a vector % norm is its infinity norm
a = [ -43 -37 24 27 37 -33 -19 29 43 -49 ]; b = [ -5 -4 -29 -29 30 33 20 31 42 14];and find the value of infinity norm of a and the two norm of b with the commands
aInfinity = infinityNorm(a) bTwo = twoNorm(b)Note that you no longer need to use the letter v to denote the vector, and it is easy to manipulate the values of the norms.
In this section you will see how to use plotting to enhance work that is
focussed on something else, like solving a differential equation.
The differential equation
% compute the solution of the differential equation % y'+y=sin(x) % starting at y=0 at x=0 using Euler's method STEPSIZE=.5; NTERMS=30; clear x y exactSolution y(1)=0; x(1)=0; exactSolution(1)=0; for k=1:NTERMS x(k+1)=x(k)+STEPSIZE; y(k+1)=y(k)+STEPSIZE*(-y(k)+sin(x(k))); exactSolution(k+1)=.5*(exp(-x(k+1))+sin(x(k+1))-cos(x(k+1))); plot(x,y); % default line color is blue axis([0,16,-1.1,1.1]); hold on plot(x,exactSolution,'g'); % g for green line legend('Euler solution','Exact solution') hold off disp('Press a key to continue.') pause endIt is always good programming practice to define constants symbolically at the beginning of a program and then to use the symbols within the program. Sometimes these special constants are called ``magic numbers.'' By convention, symbolic constants are named using all upper case.
In general, a first-order ordinary differential equation can be written
in the form
A slightly more complicated method for (4) is
Euler's implicit method, which can be written in the following way.
print -djpeg exer11.jpgwhere ``exer11'' can be any file name, but the extension should be .jpg.
Back to MATH2071 page.