By the time you complete this lab, you should be able to:
You will also get more practice with
The instructions are generally written from the standpoint of working on a SunRay.
However, you can do them from a PC or Mac. Here's how:
Once you've looked over all of those pages, you can adapt the instructions below by simply opening two SSH windows to strauss:
matlabto bring up the MATLAB prompt (>>). Any time the instructions say to type something at the Command Prompt window, use this window.
emacs foo.mto bring up emacs to edit the file
emacs -nw foo.minstead
You can review the instructions from lab01 if you are not sure how to do this.
During your time at UD, you'll likely end up using your UD Unix account for many classes—not just CISC105. So it is important to keep your files well organized. One of the first steps is to create a directory for those files. In the Unix operating system, a directory is what you may be accustomed to calling a folder under Windows or MacOS—it is a place to store a collection of files, and it has a name.
We are going to create a directory called
cisc105 (note the lowercase "
cisc"). This directory will be stored inside our home directory, which is the top level directory for all the information we store on the UD Unix systems.
When you first startup MATLAB, you should be able to find your "home directory" in the places indicated in the following diagram. The one shown in the example below is Phill Conrad's home directory (/home/usra/d9/55560). Yours will be different from that, but still in a similar format:
Figure out what your home directory is, and make a note of it.
Now, in the MATLAB command window, type pwd, like this. The answer that comes back should show you your home directory:
ans = /home/usra/d9/55560 >>
The reason is that MATLAB will typically start you off in your home directory. However, if we keep putting M-files in your home directory, after a while it will get very cluttered. So, it is good practice to create a folder (also called a sub-directory) for each course that you take where you use MATLAB.
To do this, type the following three commands in the MATLAB command window. Note the use of lowercase—in general don't use capital letters in MATLAB except when the instructions specifically indicate to do so! (An explanation of each command follows the example input/output)
>> mkdir cisc105 >> cd cisc105 >> pwd ans = /home/usra/d9/55560/cisc105 >>
mkdir cisc105, makes a new subdirectory (folder) called
cisc105. This is the folder where you will store all of your labs for this semester.
cd cisc105, changes your current directory to be
pwd, asks MATLAB to print the working directory. Note that the working directory is now your home directory with cisc105 stuck on the end of it.
Notice that the places in the MATLAB window where you saw your home directory before (the places circled in yellow above) should now show your working directory with the addition of
cisc105 stuck on the end, reflecting that this is now your "working directory". That means that this is where you will find the M-files that you store, for example.
Now that we have a directory called cisc105 under your home directory, each week we will make a separate directory for that weeks lab. We'll call these directories
lab04, and so forth.
In general, the squiggle (
~), which is more properly called the tilde, stands for your home directory.
you can use the following sequence of commands:
>> mkdir ~/cisc105/lab02 >> cd ~/cisc105/lab02 >> pwd ans = /home/usra/d9/55560/cisc105/lab02 >>
cd ..(that's cd dot dot).
cd ~(that's cd squiggle)
In general, the squiggle (
~), which is more properly called the "tilde", stands for your home directory.
cd ~that means "change directory to my home directory"
cd ~/cisc105it means "change directory to the cisc105 that is immediately under my home directory"
cd ~/cisc105/lab02it means "go into lab02, which is inside cisc105, which is inside my home directory"
Try each of these commands. Also try
cd .. after each command to see where you end up. Do this until you are comfortable with what the
howMuchPizza.mwhile in your ~/cisc105/lab02 directory
Now, use the
cd command to change into your
Next, we are going to create a MATLAB m-file to solve the following problem:
Determine how much pizza (in square inches) you get if you order two regular pizzas (12 inch round) vs. 1 x-large pizza (16 inch round).
To do this, we will "edit" a file called
The M-file editor window should come up. Put the following MATLAB commands into that file. Change the name in the file to your own, and the section to your own.
% howMuchPizza.m % 09/03/2007 Michael Haggerty for CISC105 section 99 % Script to compute how much pizza you get if you % get 2 12-inch pizzas vs. 1 x-large 16-inch pizza regPizzaDiam = 12; regPizzaRadius = regPizzaDiam / 2; regPizzaArea = pi * (regPizzaRadius ^ 2); xLargePizzaDiam = 16; xLargePizzaRadius = xLargePizzaDiam/2; xLargePizzaArea = pi * (xLargePizzaRadius ^ 2); % leave off semicolons to get output to print totalAreaTwoTwelveInchPizzas = 2 * regPizzaArea totalAreaOneSixteenInchPizza = xLargePizzaArea % end of howMuchPizza.m
Once you've typed this in ( or cut and pasted it, and changed the name and section number), try running it. Do you remember how to run an M-file once you've typed it in? If not, check lab01, and/or Chapter 1 of your textbook.
Do the answers that you get seem reasonable? Check them with a calculator, and pencil and paper work.
Once you've verified that the file works, make a diary file to document the work we've done so far. The more we practice these skills, the more they will stick in our brains.
Create a diary file called lab02a.txt. (If you are not sure about how to create a diary file, review step 6 of lab01 before proceeding.)
In your diary file, do all of the following:
pwdto show that you are in the ~/cisc105/lab02 subdirectory (the ~ will be replaced with your actual home directory)
lsto list the contents of the current directory
howMuchPizza.mfile, you might see a file called
howMuchPizza.asvor a file called
howMuchPizza.m~. This is the MATLAB "automatic save" file. Don't worry about it—it's perfectly normal. Also, don't worry if you don't see this file.
type howMuchPizza.mto list out the contents of
diary offto end the recording. You'll upload both the files
lab02a.txtto WebCT in the final step of this lab.
From time to time, you'll need to copy files from the course web site, and work with them in MATLAB. We are going to practice that in this step of the lab.
The file we want to copy is on the web at the following link:
There are several ways we could get the file from there into your directory, but the best way is a direct copy. It turns out that when you are using MATLAB on strauss, you have direct access to the hard drive where files for the UD web server are stored.
In MATLAB, to copy a file directly from one place on the disk to another, we use the
(Note that the
>> is the MATLAB prompt, not part of the command)
>> copyfile /www/htdocs/CIS/105/haggerty/07F/labs/lab02/compareGrottosPizzas.m ~/cisc105/lab02
This MATLAB command says to copy from the place where this file is stored on the hard drive, into the directory
~/cisc105/lab02. After you do this command, type
ls and you should see the file in your directory listing, like this:
>> copyfile /www/htdocs/CIS/105/haggerty/07F/labs/lab02/compareGrottosPizzas.m ~/cisc105/lab02 >> ls compareGrottosPizzas.m howMuchPizza.m >>
A few notes:
cpcommand (with filename auto-completion), and the Unix
compareGrottosPizzas.m is related to the problem you worked on in step 1, but it actually solves a different problem, namely:
Determine the price per square inch of a regular pizza (12 inch diameter round) that sells for $8.99, vs. an x-large pizza (16 in diameter round) that sells for $11.99.
(These values come from Grotto Pizza on Main St. in Newark, as of 09/03/2007, and pertain to the regular price for a plain cheese pizza.)
compareGrottosPizzas.mon the web
You can read through the file
compareGrottosPizzas.m at the following link:
Take a moment to visit this link, and look through this file. Notice each of the following things:
%). Comment lines are ignored by the MATLAB software, but are very important for any human beings (including yourself!) that might read the code.
The rest of the file is divided into sections with comments that look something like this.
%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This is a section header % %%%%%%%%%%%%%%%%%%%%%%%%%%%%
These comments have no special "meaning" in MATLAB—since they are lines that start with a percent sign, they are treated just like every other comment (i.e. they are ignored by the MATLAB software, and are there only to help humans make sense of how the code works. However, they do have a special purpose for the human reader.
When an author writes a book, she/he divides it into chapters. The chapters are divided into sections, and the sections are divided into paragraphs. These divisions make it easier to read and understand the book. Imagine how hard it would be to read a book that was not divided up in this way!
In the same way, well-written code is divided up into sections and paragraphs. We often introduce a section with a big fluffy comment like this one, and then use a smaller comment such as this one to introduce a "paragraph" of code
% compute area of both pizzas
output. This is a typical division into sections for a program. We set up some initial values, we do some calculations, then we output the results.
;) at the end of it.
You copied the
compareGrottosPizzas.m file in your directory in Step 6. Now that we've gone through the file to understand what it does, the next step is to ask MATLAB to carry out the computations in this file, and show the result.
As you already know, we can do that by simply typing the name of the file (without the
.m), like this:
>> compareGrottosPizzas ppsiRegPizza = 0.0795 ppsixLargePizza = 0.0596 >>
So, we can see that an X-Large cheese pizza from Grottos costs about 6 cents per square inch, while a regular pizza costs about 8 cents per square inch, or about 33% more, square-inch-for-square-inch.
A limitation of this file is that the values in it are hard-coded. That is, this file is only good for calculations involving Grotto Pizza. you cannot change the values without editing the
compareGrottosPizzas.m file itself.
Suppose, for example, you wanted to do a similar calculation for Pat's (on Elkton Rd), or Peace-a-Pizza (also on Main St. in Newark), using the values below:
To use this file to answer questions about Pat's or Peace-a-Pizza, we'd have to make many changes to the file. In fact, we have to edit the file and change it each time we wanted to solve another instance of the problem—Grottos being one instance, Pat's being a second instance, and Peace-A-Pizza being a third instance.
A more efficient way is to create a special type of M-file called a function M-file. A function M-file is one that can take one or more inputs, and produce a result. The nice thing about a function is that once we've written a useful function, we can plug in different values—thus solving different instances of the same problem—without having to do any extra work. That's the subject of lab02.
There is nothing to turn in or save from steps 6 and 7. However, they are important preparation for understanding the work you'll be doing in lab02, so you can't really skip them. If you skip them, you'll end up having to do them later anyway, as you start to work on lab02.
In this section, we'll define our own function to compute the area of a pizza. But first, we'll look at some of the built-in functions that MATLAB already has.
MATLAB has many built-in functions, such as
sqrt(x) (for square root of x), as well as
cos(x). Here are some examples of using built-in MATLAB functions. Try these examples in the command window of MATLAB. As you can see, if you just put a number or a variable into the parentheses, MATLAB will calculate a result.
>> sqrt(36) ans = 6 >> sqrt(49) ans = 7 >> sin(pi / 2) ans = 1 >> sin(3 * pi / 2) ans = -1 >> x = 2 * pi x = 6.2832 >> cos(x) ans = 1 >> sin(x) ans = -2.4493e-16 >>
The answer -2.4493e-16 for sin(x) where x=2π might require some explanation.
You were probably expecting that sin(2π) should be zero—or at least I hope you were expecting that! The answer MATLAB gave, i.e. -2.4493e-16 is the way that MATLAB expresses the number -2.4493 x 10-16, which is scientific notation for the number-.00000000000000024493.
That number is indeed very close to zero. A fact of life is that computers cannot exactly represent the result of any numeric computation involving numbers such as π, because such numbers contain an infinite number of significant digits. However, computers contain a finite number of memory cells, and any particular value that is stored by a computer can only use a limited number of those cells. Thus, many calculations done by computer are only approximations. They are often very good approximations, but they are approximations, nevertheless.
The built-in functions in MATLAB are so important that your Holly Moore MATLAB textbook devotes an entire chapter to this topic, called (appropriately enough) "Built-In MATLAB functions". When you are finished with this lab, a great next step would be to read through that chapter (with MATLAB handy, to try things out).
Next, you are going to copy an M-file that defines a new function into your account. Here's the command:
copyfile /www/htdocs/CIS/105/haggerty/07F/labs/lab02/areaOfPizza.m ~/cisc105/lab02
After you type in this command, type in the
ls command to "list your files" and you should see the
areaOfPizza.m in the listing of the files.
In this step, first we'll see that when you have a function M-file in your current directory, you can use the help command to learn about how to use it:
Then we'll see how to actually do computations with a MATLAB function M-file.
Now, try the following command:
You should get the following result:
>> help areaOfPizza areaOfPizza compute area of pizza, given diameter consumes: diameter: number, diameter of the pizza in inches produces: area: number, area of the pizza in square inches examples >> areaOfPizza(12) ans = 113.10 >> areaOfPizza(16) ans = 201.06 M. Haggerty cisc105 section 99, 09/03/2007 >>
The help text shows you how to use the areaOfPizza function.
Now, try typing in one of the examples yourself—for example type
areaOfPizza(12) at the MATLAB prompt. You should get a result like this one:
>> areaOfPizza(12) ans = 113.0973 >>
Note that the answer is not exactly the same as the one in the heading, but if you found off the answers to the number of significant digits shown, the answer is correct. MATLAB actually has different formats for displaying output—these affect the number of significant digits shown, and whether the answer is in regular or scientific notation. For example:
>> format long >> areaOfPizza(16) ans = 2.010619298297468e+02 >> format short >> areaOfPizza(16) ans = 201.0619 >> format short g >> areaOfPizza(16) ans = 201.06 >>
We can see here that if
format short g is selected, the answer shown in the example is exactly correct. Keep this in mind when comparing answers from MATLAB computations to the examples shown.
By now, you may be getting tired of copying files "one at a time" into your directory. So, now, we'll learn a command to copy a lot of files all at once. This command copies all of the .m files that are in the folder for this lab into your
~/cisc105/lab02 folder. The star (
*) is called a wildcard. When you write
*.m , it means "any file that ends with
.m". (Note: See update below if you have trouble with this command).
copyfile /www/htdocs/CIS/105/haggerty/07F/labs/lab02/*.m ~/cisc105/lab02
Type this command in at the prompt, and afterwards you'll find several new files when you type
UPDATE: Several students have reported problems with the above command.
Meanwhile, it seems to work fine for your professor, for the TAs, and for some students. We think we've tracked down the problem.
If the command doesn't work for you, try this one instead. It is the same as the command above, except you use
!cp instead of
copyfile. The explanation point in front of
cp tells MATLAB to run
cp as a Unix command instead of as a MATLAB command.
!cp /www/htdocs/CIS/105/haggerty/07F/labs/lab02/*.m ~/cisc105/lab02
Our best guess as to why copyfile with a wildcard didn't work for some people: The pattern seems to be that those students who have not yet changed their default shell to either /bin/tcsh or /bin/bash are the ones that experienced the problem. Pretty much all instructors and/or TAs use /bin/tcsh or /bin/bash as their login shell (we'll discuss why, and what that means in lecture.)
What you should do: As soon as possible (right now, perhaps!) please visit
http://www.udel.edu/network, click on Change default login shell, and select either
/bin/bash. If you aren't sure which one to choose, use
/bin/tcsh. This takes overnight to go into effect, so it wont affect your lab today. But it will make working at the Unix prompt a lot easier, and apparently it affects how MATLAB behaves as well.
Earlier in lab02 we worked with a type of M-file called a script M-file. In step 10 of this lab, we worked with a function M-file. Now its time to take a look at how these two compare with each other.
Now, let's compare how we might use both of these to solve the problem posed above:
Determine how much pizza (in square inches) you get if you order two regular pizzas (12 inch round) vs. 1 x-large pizza (16 inch round.)
howMuchPizza.m, the parameters to the problem are hard coded inside the script file. So, we simply type howMuchPizza at the MATLAB command prompt, and we get this:
>> howMuchPizza totalAreaTwoTwelveInchPizzas = 226.19 totalAreaOneSixteenInchPizza = 201.06 >>
areaOfPizza.m, we do a bit more typing. But notice that we can change the parameters of the problem (e.g. how many small or large pizzas, or the sizes of the pizzas) without doing any additional programming.
For example, while Grottos pizzas are 12" and 16", Pat's pizzas are 12" and 15", and Peace-a-Pizzas are 14" and 16". We can easily make comparisons such as these with no additional programming:
>> areaOfPizza(12) * 2 ans = 226.19 >> areaOfPizza(16) ans = 201.06 >> areaOfPizza(12) * 2 ans = 226.19 >> areaOfPizza(15) ans = 176.71 >> areaOfPizza(14) * 3 ans = 461.81 >> areaOfPizza(16) * 2 ans = 402.12 >>
You should not, however, come to the conclusion that this means that script files are "bad" and function M-files are "good". As we will see, they each have their proper use. And, it is often useful to use them together, as we explore in the next step.
One of the files you should have copied into your account back in Step 6 (the wildcard copy step) is this file: comparePizzas.m
Click on the link above to look at the contents of this file. Notice how it uses the areaOfPizza function we defined in areaOfPizza.m to do the computation. Thus we can type simply
comparePizzas at the MATLAB prompt and get a list of various amounts of pizza. that we can obtain by buying various quantities and sizes of pies from various shops.
>>comparePizzas twoGrottosRegular = 226.19 oneGrottosXLarge = 201.06 twoPatsMedium = 226.19 onePatsLarge = 176.71 threePeace14 = 461.81 twoPeace14 = 402.12 >>
This shows that script M-files and function M-files can work together very well.
For example, in Civil Engineering, suppose there is a general formula for determining the maximum load that a particular kind of bridge can hold.
A special kind of script that we can use with a function M-file is called a testing script. This script is used to test whether the function is working properly. There is a growing movement in software development that suggest we should write a test script before we write the function itself. That way, we will have a way to quickly determine whether our function is correct or not.
Here is an example of a test script for the areaOfPizza function called testAreaOfPizza.m
Take a look at testAreaOfPizza.m by right clicking on the filename above, and choosing "Open Link in New Window"—that way, you can continue to read these instructions, and look at the file, side-by-side.
Note the following things about this file:
else. This is a feature of MATLAB that allows an M-file to "make a decision". After the word
if, there is an expression that is either true or false.
(diff < tolerance)
diffis less than
tolerance, than that means we are "close enough" and we report that the test passes, using
disp('test 1 passes');which is a MATLAB function that displays
test 1 passesin the command window.
test 1 failed, and then print both the actual and the expected result (by just putting those variable names without any semicolons.
Now, run this testing script and notice the result. You should see something like this:
>> testAreaOfPizza test 1 passed test 2 passed >>
Of course, if we are going to have confidence in a test file, we need to know that if the areaOfPizza.m file were truly broken, the test could detect that. So, in this step, we are going to do some "evil programming". We are going to introduce a "bug" (a mistake) on purpose into the areaOfPizza.m file, just to see what will happen. When we are finished, we'll fix it back.
Go to the edit window in the MATLAB user interface, and bring up the file areaOfPizza.m. Find the three lines that compute the result:
radius = diameter / 2; area = pi * radius ^ 2; return;
Add in an extra "evil line" as shown below.
radius = diameter / 2; area = pi * radius ^ 2; area = -42; % this is an evil line---remove it later! return;
Note that on the evil line, everything after the % sign—all the way to the end of the line—is a comment, and it is ignored by MATLAB. Comments can occur not only a line by themselves, but also immediately after a MATLAB statement.
The evil line will overwrite the correct computation of the area with the number -42 (the additive inverse of a famous number in geek culture). Thus, the function will always produce an incorrect result (since a pizza can never have a negative area.)
With the evil line in place, we should get the following:
>> testAreaOfPizza test 1 failed expected = 113.1000 actual = -42 test 2 failed expected = 201.0600 actual = -42 >>
Now, take the evil line back out, and run the test again. It should be back to working properly.
In Step 15, you will be writing your own function M-file. So it is important to understand how these files works. We'll start by examining the areaOfPizza.m file more closely.
Visit the following web link to look at the file you copied into your
Notice a few things about this file:
This file starts with the following line:
function area = areaOfPizza(diameter)
This line indicates that:
The next few lines are a series of comments like this:
%areaOfPizza compute area of pizza, given diameter % % consumes: % diameter: number, diameter of the pizza in inches % produces: % area: number, area of the pizza in square inches % % examples % >> areaOfPizza(12) % ans = 113.10 % >> areaOfPizza(16) % ans = 201.06 % % P.Conrad cisc105 section 99, 09/03/2007
These comments are known as the H1 comment. They are special, because they interact with the MATLAB commands
lookfor. (We'll illustrate this below).
In this H1 comment, we see the "contract" for the function—what it expects to get (in this case, diameter) and what it promises to produce. There are also some examples of how to use the function, along with what the result should be.
Finally, we have the programmers name, information about the course and section, and the date the function was created.
In this step, you'll work with two M-files that you should find in your directory (copied when we did the wildcard copy back at step 6).
The two files are:
As you might expect, these files are similar to areaOfPizza.m and testAreaOfPizza.m, except they work on rectangular pizzas, such as the square (16"x16") and the party pizza (18" x 26") advertised by Pat's on this menu excerpt:
There is a problem with areaOfRectPizza.m however. Namely, that it doesn't work. The evil programmer has been at it, and has inserted a line that only ever returns -42 as the area of the pizza. You can verify this by running the testAreaOfRectPizza.m script:
>> testAreaOfRectPizza test 1 failed expected = 120 actual = -42 test 2 failed expected = 169 actual = -42 >>
So, your task: correct the problem in
areaOfRectPizza.m so that the tests in
testAreaOfRectPizza.m both pass.
Be sure to also change the author, date, class and section in the comments as appropriate—to your name, class, section, and the date you did the work.
Once this is done, create a diary file
lab02b.txt in which you run the commands shown below. If you are not sure about how to create a diary file, review the steps near the end of lab01.
pwd(to show you are in the correct directory, ~/cisc105/lab02)
type areaOfRectPizza.m(to list out your corrected areaOfRectPizza.m file)
testAreaOfRectPizza(to show that the tests now pass)
Log on to MyCourses (WebCT) and find cisc105 (if it is not listed, tell your TA, and email your instructor!)
Follow the instructions for submitting an Assignment in WebCT (submit this as lab02). You should submit two files:
And you are all finished!
Generally submitting everything according to instructions: 10 pts.
Adapted with permission from Phill Conrad