MATH2071: LAB #1(a): Preliminaries



Introduction Exercise 1
Starting up Matlab Exercise 2
Using a browser to download files Exercise 3
Getting help Exercise 4
Quitting Exercise 5
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
Flow control  
M-files  
Ordinary differential equations and graphics  


Introduction

You will find instructions for each lab, including this one, on the web, starting from my home page: http://www.math.pitt.edu/~sussmanm . I do not supply copies on paper. Many students find it helpful to print out copies of the lab instructions before the lab session, although it is not strictly necessary. During the lab session, it is convenient to use the online version because you can ``copy-and-paste'' instructions from the web page directly into Matlab. If you prefer, you will find a version of this lab in Adobe pdf format here.

This version of the first lab is intended only for students who did not take Math 2070.
There are two versions of the first lab. This version introduces the Matlab environment and programming language, and presents the general format of the work you need to hand in. If you have already taken Math 2070, this material would be a repetition, so you should take the alternative version of Lab 1(b).

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.


Grading

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:

A+
The work is correct, or there are only very minor errors.
A
All portions of the lab work was attempted and most of it is correct. Some serious errors are present.
B
Not all portions of the lab work was attempted.
Zero
Lab was not submitted.

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.


Starting Up Matlab

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.

  1. Start up Matlab by (a) double-clicking the icon on the status bar at the bottom (this is the fifth icon from the left in the default configuration, and looks like this: \includegraphics[scale=.06]{matlabShape.eps}), (b) choosing Matlab from the K (or Gnome or Start) menu at the lower left corner, (c) choosing ``Run Command'' from the K (or Gnome or Start) menu, or (d) typing the command matlab at a command prompt. The first window that opens is a blank white window named ``Shell-Matlab,'' and you should minimize it using the dash at its top right. The second window is the ``splash'' that identifies Matlab, and it will go away by itself. Then the main Matlab window will open up on your screen. This window will look something like the following:

    \includegraphics[scale=0.75]{lab01fig01.eps}

    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.

  2. It is a good idea to organize your work into directories (or folders-they are the same thing). I suggest that you do your work in your AFS (Andrew File System) directory. This is the same directory that unixs uses and it is permanent, unlike the default directory on the computers in GSCC. (Files left in the default home directory will disappear when you log out!) Use the Matlab ``Current Directory'' windowpane to navigate to your AFS directory. (Go first to the ``Desktop'' and then to ``AFS'' and then to ``private''.) Inside that directory, I suggest that you use a directory named math2071 for all the work in this lab, and subdirectories lab01, lab02, ..., lab10 for each of the labs. You will need to create these directories before you can use them, and the ``Current Directory'' windowpane has the appropriate buttons. After a directory has been created, you can also use the small box named ``Current Directory'' in the middle of the line of icons near the top of the Matlab window.

    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 private
    
    You create a directory named math2071 with the commands
    mkdir math2071
    
    and you can make it the current directory with the command
    cd math2071
    
    You can always find the name of your current directory with the command
    pwd
    
    and you can get a listing of the files in the current directory with either the command
    dir
    
    or the command
    ls
    

    Before going on, create the directory math2071, with subdirectories lab01, lab02, ..., lab10.

  3. The ``Command History'' windowpane is convenient for recalling what commands you have used recently. In addition, Matlab provides the capability to keep a record of both the commands and their output. The command to do this is
    diary diary.txt
    
    The 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.

  4. Note that you can double-click a command in the ``Command History'' windowpane and it will be executed again. You can also drag a command into the ``Command'' windowpane and then change it using the arrow keys.

  5. You can also recover old commands by using the up-arrow key and then change them using the right and left arrow keys.

  6. As will be described below, you will be sending your files to me by email. Since there are sometimes a large number of these files, it is inconvenient to attach them one by one, so I suggest you create a ``zip'' file. Before you create the ``zip'' file, exit your diary with the command diary. If you do not, your diary will be incomplete in the ``zip'' file. You can create the ``zip'' file from the Matlab command line with the command
    !zip labfiles.zip *.m *.jpg *.txt
    
    where ``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.

  7. After you have completed a lab, exit from Matlab with the command quit or use the File$\rightarrow$Close Matlab menu choice.


Using a USB drive

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.


Using a browser to download files

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.

Exercise 1: If you are not using the online version of this lab, please start it up by starting the browser and finding the online version of this page, beginning from my home page,
http://www.math.pitt.edu/~sussmanm, clicking on Math2071, and then on Lab #1.

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: math2071/lab01, 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.m
or by double-clicking on the file in the ``Current Directory'' windowpane, or using the ``File$\rightarrow$Open'' 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.

Exercise 2:
  1. Turn on debugging with the commands
    dbstop if error
    dbstop if naninf
    
    or through the Breakpoints menu on the Edit window.
  2. Now, look at demoscript.m in the edit window. At the bottom there is a statement %bad=1/(x-1);. The percent is a comment character, so this statement is not executed. Make this statement active by deleting the percent character and save the changed file.
  3. Execute the script file by typing its name without the .m at the command line or by choosing ``Run'' from the Debug menu on the Edit window.
  4. The division by zero caused an exception and Matlab popped up a window with the offending source line highlighted. You should also note the changed prompt in the command window.
  5. Place the mouse pointer on top of the x in the expression bad=1/(x-1) and leave it there motionless for a second or so (this is called ``hovering''). The value of x should be displayed. You can then see why the error occurred.
  6. Look at the prompt in the command window. It has changed to . You can do any legal Matlab command at this changed prompt. In particular, you can type the name x to get Matlab to print out its value. This is an alternative way to see the value of a variable in a debug situation.
  7. You can exit from debugging mode either using the menu in the edit window or with the command
    dbquit
    
    This action will return Matlab to its usual » prompt.
  8. You can turn off debugging feature with the command
    dbclear all
    
    or 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.

Exercise 3:
  1. Type the command clear at the command line. This will return Matlab to its state just after starting up. No variables will show in the ``Workspace'' windowpane.
  2. Click on the first executable line (x=1.3) of the demoscript.m file. You will notice a column of dashes to the left of the code, and you can ``set'' a ``breakpoint'' by clicking on the dash. Alternatively, go to the ``Breakpoints'' menu and ``set'' a breakpoint there. One of the buttons at the top of the window will also set a breakpoint. When a breakpoint is set, a red dot will be placed next to the line number in the edit window.
  3. Begin executing the file either by choosing ``Run'' from the debug menu, by pressing the ``Run'' button, or by typing the name demoscript at the command line. The edit window will show that the script is poised to execute the first line of the file. (That line has not yet been executed.)
  4. Predict, in your mind, what will happen when the line is executed. In this case, the value of x will change to 1.3 and the result ``x=1.3'' will be printed because there is no semicolon at the end of the line.
  5. Choose ``Step'' from the Debug menu , press the ``Step'' button (hovering over a button brings up its description) or issue the command ``dbstep'' at the command line. This will cause the current line (line 8) to be executed. You will see the variable x appear in the Workspace windowpane and x=1.3000 appear in the command window.
  6. Predict what will happen on the next step. What will the value of the variable xsquared become?
  7. Predict what will happen on the next step. What will the value of the variable p become? (An estimate is good enough.)
  8. Continue using ``Step'' and watch the script execute, one line at a time.
  9. If the next line were to call a function, the button next to the ``Step'' button is the ``Step in'' button. The ``Step'' button goes on, using the value of the function while the ``Step in'' button jumps to the code inside the function and steps there.
  10. Pressing the ``Continue'' button causes Matlab to continue executing the script until another breakpoint is reached or until the end of the script is reached.
  11. Press the ``End Debugging'' button to exit from debug mode. Alternatively, choose Debug->Exit Debug Mode from the menus or use the command dbquit.


Getting help

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 diary
You 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 demoscript
will 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.

helpdesk
This 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:
http://www.mathworks.com/access/helpdesk/help/techdoc/ We will be looking at the help facility on the web later in this lab.


Quitting

You exit Matlab by typing quit at the command line or by using the File$\rightarrow$Exit menu choice.


Lab summaries

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:

  1. Those parts of the answers to each exercise that I ask for.
  2. Explanations of what you did, in full sentences.
  3. I would like to see a few lines expressing your opinion of the point of each exercise.
  4. Easily identified answers to exercises, including numerical values. I do not want to look in your diary file to try to figure out what you did.
Here is what I do NOT want to see in the summary file:
  1. Matlab error messages (unless I ask for them).
  2. False starts, mistyped commands, etc.
  3. Incorrect results that are corrected later.
  4. Duplications of anything, unless I explicitly ask for them.
  5. Large numbers of printed values, for example, the contents of a vector of length 100. I will not read all these numbers and they end up being like spam.

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.


More on Matlab

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.

  1. What is a matrix in Matlab? What is a vector? How are they different from plain numbers?
  2. How to you refer to the elements of a matrix or vector in Matlab?
  3. How to you use a colon to represent a range of numbers or subscripts?
  4. What symbols are associated with the elementary arithmetic operations? (Addition, multiplication, exponentiation, etc.)
  5. What meanings do the special constants pi, i, j, inf (infinity), and NaN (not-a-number) have?
  6. How do you use the ellipsis ... to put a single statement on more than one line?
  7. What are script m-files? What are function m-files? What is the difference?
  8. What does format long mean and what other options might be useful?
  9. How are the arrow keys used to edit commands in the command window?
  10. What is the form of the plot command?
  11. What are the hold on and hold off commands used for?
  12. How do you indicate matrix sum, product, inverse, and transpose?
  13. What do the element-by-element matrix operations such as product mean and how are they denoted?
  14. What is an if ... else ... end statement used for? Can you give an example?
  15. How do you use the for statement to write a loop?
  16. How is the break statement used in a loop?
  17. What is the feval statement used for?

The following sections discuss more of the use of Matlab. I will expect a summary of your work for the rest of this lab.


Matlab files

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

function output variable = function name (parameters)
This defining line is called the ``signature'' of the function. The output variable and parameters can be missing. The name of the function must be the same as the file name. Comment lines should include the following.
The first line following the signature should repeat the signature (I often leave out the word ``function'') to provide a reminder of the usage of the function.
Brief description of the mathematical task the function performs.
Description of all the input parameters.
Description of all the output parameters.
Your name and the date.
Part of the first of these lines is displayed in the ``Current directory'' windowpane, and the lines themselves comprise the response to the Matlab command help <function>.

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.


Variables and values

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 $6.022\cdot10^{23}$ in usual scientific notation, but Matlab would write this as 6.022e+23. The e denotes $10^{}$. 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 $1\times1$ 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 secondVariable
should 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

ans: The result of the previous calculation.
computer: The type of computer you are on.
eps: The smallest positive number $\epsilon$ that satisfies the expression $1+\epsilon>1$. This value indicates the size of ``roundoff.'' (Note: The name eps is a special name, and it means a particular value. It is not the same as a variable named epsilon, which could take any value.)
i, j: The imaginary unit ($\sqrt{-1}$). In this course you should avoid using i or j as subscripts or loop indices.
inf: Infinity ($\infty$). This will be the result of dividing 1 by 0.
NaN: ``Not a number.'' This will be the result of dividing 0 by 0, inf by inf, etc.
pi: $\pi$
realmax, realmin: The largest and smallest real numbers that can be represented on this computer.
version: The version of Matlab you are running. (The ver command gives more detailed information.)

Exercise 4: Start up Matlab and use it to answer the following questions.
  1. What are the values of the reserved variables pi, eps, realmax, and realmin?
  2. Choose a value and set the variable x to that value.
  3. What is the square of x? Its cube?
  4. Choose an angle $\theta$ (pick one whose $\sin$ and $\cos$ you know) and set the variable theta to its value.
  5. What is $\sin\theta$? $\cos\theta$? Is the angle $\theta$ interpreted as degrees or radians?
  6. Use the save command to save all your variables.
  7. Use the clear command. Check that there are no variables left in the ``current workspace'' (windowpane is empty).
  8. Restore all the variables with load and check that the variables have been restored to the ``Current workspace'' windowpane.


Variables are matrices

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 : finish
or
start : finish
in 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 : 20
and 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

Exercise 5:
  1. Use the linspace function to create a row vector called meshPoints containing exactly 100 elements with values evenly spaced between -1 and 1.
  2. What expression will yield the value of the $37^{\mbox{th}}$ element of meshPoints? What is this value?
  3. Double-click on the variable meshPoints in the ``Current workspace'' windowpane to view it as a vector and confirm its length is 100.
  4. Produce a plot of a sinusoid on the interval $[-1,1]$ using the command
    plot(meshPoints, sin(2*pi*meshPoints))
    
    Please save (export) this plot as a jpeg (.jpg) file and include it with your summary.
  5. Create a file named exer5.m (you can use the Matlab command edit, type the commands into the window and use ''Save as'' to give it a name). The first lines of the file should be the following:
    % Lab 1, exercise 5
    % A sample script file.
    % Your name and the date
    
    Follow 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 Debug$\rightarrow$Run from the edit window menus.


Vector Operations

Matlab provides a large assembly of tools for matrix and vector manipulation. We will investigate a few of these by trying them out.

Exercise 6: Define the following vectors and matrices:
rowVec1 = [ -1 -4 -9]
colVec1 = [ 2
            4
           -8 ]
mat1 = [ 1  3  5
         7  9  2
         4  6  8 ]
  1. You can multiply vectors by constants. Compute
    colVec2 = (pi/4) * colVec1
    
  2. The cosine function can be applied to a vector to yield a vector of cosines. Compute
    colVec2 = cos( colVec2 )
    
    Note that the values of colVec2 have been overwritten. Are these the values you expect?
  3. You can add vectors and multiply by scalars. Compute
    colVec3 = colVec1 + 2 * colVec2
    
  4. Matlab will not allow you to do illegal operations! Try to compute
    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.
  5. You can do row-column matrix multiplication. Compute
    colvec4 = mat1 * colVec1
    
  6. A single quote following a matrix or vector indicates a (Hermitian) transpose.
    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 ``.'''.
  7. Transposes allow the usual operations. You might find ${\bf u}^T{\bf v}$ a useful expression to compute the dot (inner) product ${\bf u}\cdot{\bf v}$ (although there is a dot function in Matlab).
    mat2 = mat1 * mat1'     % mat2 is symmetric
    rowVec2 = rowVec1 * mat1
    dotProduct = colVec3' * colVec1
    euclideanNorm = sqrt( colVec2' * colVec2 )
    
  8. Matrix operations such as determinant and trace are available, too.
    determinant = det( mat1 )
    traceOfMat1 = trace( mat1 )
    
  9. You can pick certain elements out of a vector, too. Find the smallest element in a vector rowVec1.
    min(rowVec1)
    
  10. The min and max functions work along one dimension at a time. They produce vectors when applied to matrices.
    max(mat1)
    
  11. You can compose vector and matrix functions. For example, use the following expression to compute the max norm of a vector.
    max(abs(colVec1))
    
  12. How would you find the single smallest element of a matrix?
  13. As you know, a magic square is a matrix all of whose row sums, column sums and the sums of the two diagonals are the same. (One diagonal of a matrix goes from the top left to the bottom right, the other diagonal goes from top right to bottom left.) Show by direct computation that if
    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.
    Hints:
    • Use the Matlab min and max functions.
    • Recall that sum applied to a matrix yields a row vector whose values are the sums of the columns.
    • The Matlib function diag extracts the diagonal of a matrix, and the composed function sum(diag(fliplr(A))) computes the sum of the other diagonal.
  14. Suppose we want a table of integers from 0 to 10, their squares and cubes. We could start with
    integers = 0 : 10
    
    but 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']
    
  15. Watch out when you use vectors. The multiplication, division and exponentiation operators all have two possible forms, depending on whether you want to operate on the arrays, or on the elements in the arrays. In all these cases, you need to use the period notation to force elementwise operations. Compute squareIntegers alternatively using the exponentiation operator as:
    squareIntegers = integers .^ 2
    
    These problems never come up with addition or subtraction; nor do they occur with division or multiplication by a scalar.
  16. Matlab will allow you to be sloppy with addition. You can add a constant to each component of a vector in the following way.
    squaresPlus1 = squareIntegers + 1
    
  17. Beware when you use division with vectors or matrices! Matlab will ``divide'' one matrix by another using the Moore-Penrose pseudoinverse, and the result is rarely what you expect! A common mistake is to forget the dot in front of a division symbol, giving an incorrect result without any error messages. Look at the difference between the following two commands.
    cubeIntegers ./ squaresPlus1
    cubeIntegers  / squaresPlus1
    
  18. The index notation can also be used to refer to a subset of elements of the array. With the start:increment:finish notation, we can refer to a range of indices. Two-dimensional vectors and matrices can be constructed by leaving out some elements of our three-dimensional ones. For example, submatrices an be constructed from tableOfPowers. (The end function in Matlab means the last value of that dimension.)
    tableOfCubes = tableOfPowers(:,[1,3])
    tableOfOddCubes = tableOfPowers(2:2:end,[1,3])
    tableOfEvenFourths = tableOfPowers(1:2:end,1:3:4)
    
  19. Use the Matlab function magic it to construct a $10\times10$ matrix:
    A = magic(10)
    
    What commands would be needed to generate the four $5\times5$ matrices in the upper left quarter, the upper right quarter, the lower left quarter, and the lower right quarter of A?


Flow control

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



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
end



The syntax of a simple if statement is

if logical condition
    Matlab statement ...
    ...
end



The syntax of a compound if statement is

if logical condition
    Matlab statement ...
    ...
elseif logical condition
    ...
else
    ...
end

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.

Exercise 7: The ``max'' or ``sup'' or ``infinity'' norm of a vector is given as the maximum of the absolute values of the components of the vector. Suppose $\{v_n\}_{n=1,\dots,N}$ is a vector in $\mathbb{R}^N$, then the infinity norm is given as
\begin{displaymath}
\Vert v\Vert _\infty=\max_{n=1,\dots,N}{\vert v_n\vert}
\end{displaymath} (1)

If v is a Matlab vector, then the Matlab function length gives its length, and the following code will compute the infinity norm. Note how indentation helps make the code understandable.
% 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
  1. Define a vector as
    v=[ -5 2 0 6 8 -1 -3 -10 ];
    
  2. How many elements does v have? Does that agree with the result of the length function?
  3. Use cut-and-paste to put the above code into the Matlab command windowpane and execute it.
  4. What is the first value that norm takes on?
  5. How many times is the statement with the comment ``largest value up to now'' executed?
  6. What are all the values taken by the variable norm?
  7. What is the final value of norm?


M-files

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.

Exercise 8:
  1. Use cut-and-paste to copy the code given above for the infinity norm into a file named exer8a.m. Recall you can get an editor window from the File$\rightarrow$New$\rightarrow$M-file menu or from the edit command in the command windowpane.
  2. Add your name and the date below the introductory comment. You should always place your name and the date in an m-file. Don't forget to save the file.
  3. Redefine the vector
    v = [-35 -20 38 49 4 -42 -9 0 -44 -34];
    
  4. Execute the script m-file you just created by typing just its name (exer8a) without the .m extension in the command windowpane. What is the infinity norm of this vector?
  5. The usual Euclidean or 2- norm is defined as
    \begin{displaymath}
\Vert v\Vert _2=\sqrt{\sum_1^N v_n^2}
\end{displaymath} (2)

    Copy the following Matlab code to compute the 2-norm into a file named exer8b.m. Be sure to add your name and the date to the comments.
    % 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
    
  6. Using the same vector v, execute the script exer8b. What are the first four values the variable norm takes on? What is its final value?
  7. Look carefully at the mathematical expression (2) and the Matlab code in exer8b.m. This is the way one translates mathematical summations into Matlab code.

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, $\Vert v\Vert _2+1/\Vert w\Vert _\infty$. 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.

Exercise 9:
  1. Copy the file exer8a.m to a file named infinityNorm.m. (You can use ``save as'' or cut-and-paste to do this.) Add the following lines to the beginning of the file:
    function norm=infinityNorm(v)
    % norm=infinityNorm(v)
    % v is a vector
    % norm is its infinity norm
    
  2. The first line of a function m-file is called the ``signature'' of the function. The first comment line repeats the signature in order to explain the ``usage'' of the funciton. Subsequent comments explain the parameters (such as v) and the output (such as norm) and, if possible, briefly explain the methods used. You should have one line with your name and the date. The function name and the file name must agree.
  3. Place a semicolon on the last line of the file so that nothing will normally be printed by the function.
  4. Invoke the function in the command windowpane by typing
    infinityNorm(v)
    
  5. Repeat the above steps to define a function named twoNorm.m from the code in exer8b.m. Be sure to put comments in correctly.
  6. Define two vectors
    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.
  7. What Matlab expression would yield the value $\Vert a\Vert _2+1/\Vert b\Vert _\infty$? What is this value?


Ordinary differential equations and graphics

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

\begin{displaymath}y'=-y+\sin x\end{displaymath}

with initial condition $y(0)=0$ has an exact solution $y(x)=.5*(e^{-x}+\sin x-\cos x)$. It also has an approximate numerical solution defined by Euler's formula (see below for more detail) as
\begin{displaymath}
y_{k+1}= y_k+h*(-y_k+\sin x_k).
\end{displaymath} (3)

In some sense, $y(x_{k+1})\approx y_{k+1}$ We are going to look at how this expression evolves for $x>0$.

Exercise 10: Copy the following text into a file named exer10.m and then answer the questions about the code.
% 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
end
It 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.

  1. Add your name and the date to the comments at the beginning of the file.
  2. How is the Matlab variable x related to the dummy variable $x$ in Equation (3)? (Please use no more than one sentence for the answer.)
  3. How is the Matlab statement that begins y(k+1)=... related to the expression in Equation (3)? (Please use no more than one sentence for the answer.)
  4. In your own words, what does the Matlab function clear do? You can use the Matlab command help clear to get this information.
  5. Use the Matlab help facility to see what the plot commands, the two hold commands, the axis command, the pause command, and the legend command do.
  6. Execute the script by typing its name exer10 at the command line. The script displays a plot and waits for you to hit the ``enter'' key to track evolution of the solution. You do not have to send me these plots.

In general, a first-order ordinary differential equation can be written in the form

\begin{displaymath}
y'=f(x,y)
\end{displaymath} (4)

where $y'=\frac{dy}{dx}$. Such an equation needs an initial condition $y(x_0)=x_0$. Perhaps the simplest method for numerically finding a solution of (4) is to use the ``explicit Euler'' method wherein a discrete selection of points $x_k=x_0+h*(k-1)$ where $h$ is some fixed step size and $k=1,2,3,\dots$. Writing the approximate value of $y(x_k)$ as $y_k$, then Euler's explicit method can be derived by approximating the derivative $(y')_k\approx(y_{k+1}-y_k)/h$ and writing
\begin{displaymath}
y_{k+1}=y_k+hf(x_k,y_k)
\end{displaymath} (5)

This method can be compared with the following expression appearing in exer10.m.
  y(k+1)=y(k)+STEPSIZE*(-y(k)+sin(x(k)));

A slightly more complicated method for (4) is Euler's implicit method, which can be written in the following way.

\begin{displaymath}
y_{k+1}=y_k+hf(x_{k+1},y_{k+1})
\end{displaymath} (6)

This method is ``implicit'' because (6) is not a formula for $y_{k+1}$ but instead must be solved to find $y_{k+1}$. In the case under consideration, where $f(x,y)=-y+\sin x$, it is easy to solve (6) for $y_{k+1}$ because (6) is a linear equation. You have learned (or will soon learn) in class that the payoff for the greater complication of solving a system is that a larger stepsize can be taken while maintaining stability.

Exercise 11:
  1. Copy exer10.m to a new script m-file named exer11.m. Modify it so that Euler's implict method is used instead of Euler's explicit method. Be sure to modify your comments as necessary.
  2. What are the final values of x and y? (You can print the final value of the vector y using the special Matlab subscript ``end'' by writing y(end).
  3. Please include the final plot with your summary. You can save (export) it as a ``jpeg'' file from the file menu on the plot window or by using the command
    print -djpeg exer11.jpg
    
    where ``exer11'' can be any file name, but the extension should be .jpg.

Back to MATH2071 page.





Mike Sussman 2009-01-03