In this activity, we will give you some practice with the if/else control structure (from chapter 8 in the MHM textbook):
In the process, we'll talk about how to refactor some of our test code to make it easier to work with.
We'll learn about a few MATLAB functions:
We'll learn about concatenating character strings by constructing new matrices with [ ]
So, you are getting a head start on that.
By the time you complete this activity, you should be able to:
mod(x,m)
function will be for simple values of x and mdisp
and fprintf
will be for certain simple cases (as illustrated later in this lab.) To prepare for this week's lab, do all the following steps. If you are not sure what to do at any stage, you can consult earlier labs for details:
~/cisc106/09.26
/www/htdocs/CIS/106/pconrad/07F/lect/09.26.8am
into your new directory ~/cisc106/09.26
In this step, you'll learn a bit about two useful MATLAB functions that print output, namely:
You'll also learn about working with MATLAB variables that store text. In MATLAB these variables are called character arrays. They are also sometimes called strings.
You could easily skip this step, and your instructor or TA would never know. Until, that is, you
Then, we'll know. So, don't skip this step.
disp
vs. fprintf
, part 1—the newline thingySo, both disp
and fprintf
can be used to print out stuff. Try these commands at the MATLAB prompt:
>> disp('hello'); hello >> fprintf('hello'); hello>>
Notice how the MATLAB prompt >>
comes immediately after the second hello
.
Right away, we see one difference between disp
and fprintf
—disp
prints its output and moves to a new line, but fprintf
doesn't.
If we want a new line after hello with fprintf
, we need to put \n
at the end of our string:
>> fprintf('hello\n'); hello >>
If we put a \n at the end of a character string with disp, what will happen? You might expect that we would get an extra new line, but that is not what happens:
>> disp('hello\n'); hello\n >>
In MATLAB, \n
is only interpreted as a new line character when it is used with fprintf
. Indeed, if we include \n in a character array, it is interpreted as two separate characters. Notice the size is 1x2
.
>> x='\n' x = \n >> whos x Name Size Bytes Class Attributes x 1x2 4 char >>
(We'll see later that in C++, this is not the case—In C++, as in Java and many other languages, \n
is always interpreted as a single character, namely the newline character.)
disp
vs. fprintf
, part 2 —printing variables When using disp
, if you put something in quotes, it prints out the value literally. If you don't put that thing in quotes, it interprets it as the name of a variable, and tries to print the value. For example, notice the difference between disp('x');
and disp(x);
>> x = 5; >> disp('x'); x >> disp(x); 5 >>
If we try this with fprintf, we get different results:
>> x = 7; >> fprintf('x'); x>> fprintf(x); ??? Error using ==> fprintf No format string. >>
In the first case, fprintf('x');
prints x
just like we expected—and without going to a new line before the MATLAB prompt >>
, just as we expected. But in the second case, fprintf(x)
, we get an error: No format string.
What is the reason?
The reason is this: fprintf must always have a string as its first argument.
For example, suppose we write an assignment statement to give a value to x
. We can then use fprintf
to print the string x=
followed by the value of x
, and then go to a new line, like this:
>> x = 3 + 4;
>> fprintf('x=%f\n',x);
x=7.000000
>>
The %f stands in place of where the variable x will be printed, and the \n stands in place of where the new line character will go.
There are many other options for the format string, and it is also possible to print multiple variables in a single format string. Read more about format strings in your "Matlab, by Holly Moore" textbook: Chapter 7, section 2, "Output Options".
Another important concept is the concept of combining character strings.
Suppose we assign values as follows:
>> fname = 'Fred'; >> lname = 'Flintstone';
Then we can combine the two names into one by combining them inside a set of [ ]. This takes the the character arrays and sticks them together:
>> fullName = [fname lname] fullName = FredFlintstone >>
We sometimes call this operation string concatenation—this is a fancy computer science way of saying "stick 'em together".
Notice that the full name ended up with a space between Fred and Flintstone. We can fix this by including a space when we do the concatenation operation:
>> fullName = [fname ' ' lname] fullName = Fred Flintstone >>
We'll use this string concatenation trick inside one of the function M-files later in this lab.
The if/else statement is covered in chapter 8 of your MATLAB, by Holly Moore textbook, in Section 4, "Selection Structure". It would be helpful to review that section prior to doing this step in the lab.
We've already seen the if/else statement in the test scripts from lab03 and lab04. Take a look at each of these, and remind yourself of the places you've already seen the if/else, and how it works.
The if/else is also useful in writing certain function M-files. For example, we can write a function M-file that tests whether a number is odd or even. Look at the function M-file isOdd.m
that you copied into your directory in Step 1.
Try typing each of the following at the MATLAB prompt. Notice that in each case, the answer 1
indicates true, while the answer 0
indicates false.
isOdd(3)
isOdd(4)
isOdd(5)
isOdd(-7)
isOdd(-2)
isOdd(0)
The isOdd()
function uses the built-in MATLAB function mod()
, which computes the remainder after integer division, to determine whether a number is odd or even. Before we go further, we need to understand this mod
function
mod(x,2)
means "divide the number x by 2. If two is evenly divisible by 2, then return 0, but if x is not evenly divisible by 2, return the remainder." mod(27,3)
at the MATLAB prompt. Notice that MATLAB returns 0 because Then try:
mod(28,3)
mod(29,3)
mod(30,3)
mod(31,3)
mod(32,3)
mod(33,3)
mod
may appear on one of the exams. mod(10,5) |
mod(11,5) |
mod(12,5) |
mod(13,5) |
mod(14,5) |
mod(15,5) |
mod(20,5) |
mod(21,5) |
mod(35,5) |
mod(34,5) |
mod(1500,5) |
mod(1501,5) |
mod(27,10) |
mod(13,10) |
mod(5,10) |
mod(10,5) |
mod(7,7) |
mod(14,7) |
mod(15,7) |
mod(3,4) |
mod(4,3) |
mod(16,4) |
mod(4,16) |
mod(17,4) |
mod(16,1) |
mod(1,16) |
mod(17,16) |
mod(16,16) |
mod(135,137) |
mod(137,135) |
Among the files you copied for this week's lab are two testing scripts for the isOdd function:
Look first at the script testIsOdd.m
. You'll see that this script looks very much like all the testing scripts we've seen before. There is one exception: since we are dealing only with the values false
and true
, we can directly test if (actual == expected)
. There is no need to use a tolerance
value and test the difference between the actual
and expected
values, as we did in earlier scripts.
Next, run the testIsOdd.m script, as shown here:
>> testIsOdd test 1 passed test 2 passed test 3 passed test 4 passed >>
You can see that all four tests pass. Now try running the alternative test script, test2IsOdd.m:
>> test2IsOdd test 1 passed test 2 passed test 3 passed test 4 passed test 5 passed >>
Since test2IsOdd.m
has five tests rather than four, you might expect it to be a longer script. But look inside, and there is a surprise—test2IsOdd
is actually a much shorter script.
We can measure how much shorter by using the Unix command wc -l filename
, which tells us how many lines are in a file. (Remember to type these at a Unix prompt, not at a MATLAB prompt—or, you can type them inside MATLAB if you precede them with an exclamation point):
> wc -l testIsOdd.m 84 testIsOdd.m > wc -l test2IsOdd.m 13 test2IsOdd.m >
This output tells us that testIsOdd.m contains 84 lines, while test2IsOdd.m contains only 13. How is it that test2IsOdd.m
gets more work done with 84.5% less code (of course, I computed this using MATLAB...)
>> (84 - 13)/84 ans =
0.8452
>>
Look inside the file test2IsOdd.m
and you can find the answer—there is another function M-file involved. Locate this other helper function, and look inside and try to understand how this works.
Notice especially the line of code:
disp(['test ' testNum ' passed']);
Do you see how this uses the skills we learned in step 2?
Once you've understood how the test2IsOdd.m
file and its companion function M-file, you can now tackle the next step.
Back in lab04, you worked produced a function M-file called distance.m
to compute the distance function. In lab04, a test file called testDistance.m
was supplied for you.
This activity also contains a version of testDistance.m
, but it is different. Use the links below to compare the two files:
The new version of testDistance.m
uses a function M-file to partially automate the repeated testing—similar to the way that test2IsOdd.m
did —but in this case I have not supplied you with that function M-file. Your job is to supply the missing file.
First, copy your distance.m
function M-file from your ~/cisc106/lab04
directory into your ~/cisc106/09.26
directory. (By now, you should know the Unix command to do that—this represents a potential exam question!)
Then, look over the testDistance.m
file from this week's lab. Notice the lines such as these:
performDiffTest( distance(1,5,-2,1), 5, 0.001, '1'); performDiffTest( distance(-2,-3,-4,4), 7.28, 0.001, '2');To supply an M-file that makes these lines possible, the first line of the function M-file you need to write should be as follows:
function result = performDiffTest(actual,expected,tolerance,testNum)
This first line is sometimes called the contract, and is also sometimes called the function prototype. From this function prototype, you can determine the name of the file you will need.
Write this file, and then test it by running the testDistance script at the MATLAB prompt. You should get the following output:
>> testDistance test 1 passed test 2 passed >>
When you get this, you are finished with today's activity. You'll document this step later as part of a diary file for lab06.