CS100 Spring 1998

Assignment 7

Matlab

Part A

Due: at the end of lecture Tuesday March 31

Assignments will not be accepted late

Important Note: This handout contains a discussion of Matlab followed by Part A of your assignment 7. Part B will be handed out in lecture right after break.

The assignment can be handed in before the due date at Carpenter. Type your name and section day/time/instructor in a comment at the top of your assignment and sign the front page. It is also helpful if you highlight your name and the name of your partner with a highlighting pen.

Working with others: For this assignment, you may work with one other person. If you do, then you must actually do the work together; sit at a computer together, and make changes together. It is not proper for one person to do the work and then to add someone else's name to it. If you work with someone else, then hand in only one assignment; put both person's name, id and section information on it.

Grading of the assignment: There are two parts to this assignment. Each part will be given a grade of 0 to 3 for correctness and 0 to 3 for style and structure, for a total of a possible 6 points in correctness and 6 in style. Since part A is simply a sequence of short exercises, your style grade will depend on appropriate use of comments as you are working. You do not need to put in lots of comments, but add a few to illustrate ways to annotate the code. For part B you will be writing some functions and doing a more complicated problem. So this should be commented more thoroughly. In calculating your final grade this assignment will be worth the same as the other assignments.

The goal of this assignment: The goal of this assignment is to get you working with Matlab. Try to spend some time experimenting with Matlab and trying out different commands rather than just doing the assignment.

Introductory Comments: In this handout we first give a summary of some Matlab commands and operations that you need to know. Some of this is review of concepts you have already seen. The main focus of this assignment is on how to create and manipulate one and two dimensional arrays in Matlab. We have included examples that should help you learn the concepts quickly. You should also look over the handout called The CS100 Matlab Syllabus that we gave you in lecture. It contains a nice compact list with examples for most of the commands you need to know.

If you have purchased the book by Pratap we recommend that you work through the tutorials in the first two chapters. These are fairly quick and very well designed. Chapter 3 is a good source of information on arrays. If you purchased the book by Hanselman and Littlefield, look at chpaters 1-4. There is a lot more there than you need to know, so just pick out the relevant material. You should also find the online help feature very useful. Note: When you use the help command, you will notice that any function names and variables are capitalized in the response that appears on your screen. All of these functions actually have names that are in lower case. So you must type their names in lower case letters when you use them, e.g. use the name sum rather than SUM.

After the following summary of the commands you will find your assignment. The assignment consists of two parts. The first part (Part A) contains a sequence of exercises for you to do. These should not take you long, but it is important that you do them and then experiment some more until you are comfortable with the concepts you are learning. The second part (Part B) looks at the survey that we took in class last week and has you use Matlab to do a statistical analysis of the survey.

What to Turn In: For each of the two parts of this assignment you are to follow the directions given and turn in a copy of the command window, any graphs you produce, and all the files you create.

I. General Overview of Matlab

Types: The basic type in Matlab is arrays of complex numbers. So, an integer value or variable is really just a 1x1 array containing the integer value. A one-dimensional array is called a vector, a two-dimensional array is called a matrix, and a single number (an integer, real number, or complex number) is called a scalar. A scalar is really just an array with one row and one column, but it is treated just as we treat numerical values in Java. This is common terminology, so you will find it used in most books on Matlab. In this handout and in the texts on Matlab the term matrix is also often used loosely to refer to either one or two dimensional arrays. Because the complex numbers are built into the Matlab environment we can work with them easily. But you do not need to think in terms of complex numbers or use them at all unless you want to.

Operations and Functions: There are many built-in operations and functions. Here are just a few.

• For complex (and real) numbers we have the usual operations of +, -, *, /, and ^ The symbol ^ means exponentiation.

• Typical functions are sin, cos, log, sqrt, log10, round, etc.

• Variables are created by just assigning them values. For example, if the variable x has not already been defined, the command

>> x = 5

creates a new variable called x and initializes it to the value 5. If x already exists it simply assigns the variable the new value 5 instead.

• As in Java, we have built-in realtional operators and operators for boolean valued expressions. <, <=, > >=, == are used as in Java. The symbol for "does not equal" is ~= (the tilda symbol followed by an equals sign). The symbols for AND, OR, NOT are &, |, ~ . Matlab also has the symbol xor for the operation of EXCLUSIVE OR. The expression p xor q is true whenever p is true or q is true but they are not both true. That is, p xor q has the same meaning as the expression (p | q) & ~ ( p & q) .

In Matlab, 0 is equivalent to false and 1 is equivalent to true. We determine whether 0 and 1 are to be treated as truth values or as numbers by looking at the context in which they appear. For example, the statement

x = (3 > 5) assigns the value 0 to x. More generally, any number that is not equal to zero is evaluated as true in a context in which it is used as a boolean value. For example, x = !3 assigns x the value 0, since 3 is treated as having value true, so !3 is false. (A bit strange but you get used to it here and in C, and it can be very useful.)

Entering commands: As you have already seen, you can type in either an expression or a command by the prompt symbol » in the command window. If you type in an expression it evaluates the expression and prints the result in the window. If you type in a command such as an assignment statement it carries out the assignment and then displays the value that was assigned. If the line typed has a semi-colon at the end of it, then no value is displayed. If you typed in a graphics command the command is executed in a graphics window. If you cannot fit a command all on one line type 3 dots (...) before hitting the return and continue on the next line. When you use the 3 dots Matlab treats your command as if it were all on one line, ignoring the return. All of these facts apply to expressions and commands typed into a script or function file as well.

Example:

>> a = 5

5

>> b = 7;

>> c = a + b

12

>> b

7

II. Using Arrays in Matlab

The real power of Matlab becomes apparent when you see how easy it is to do operations on arrays. As we show you some of these operations, think about how you would implement them in a programming language like Java.

Some useful features:

• Matrix variables are dynamically managed in Matlab. This means we can add or delete rows and columns in a matrix.

• Because type matrix is the basic type in Matlab there are many built-in operations and functions that can be applied to them.

Defining a Matrix or Vector Variable: The easiest way to define an array variable is to assign it a list of values.

Examples:

>> A = [10 15 20] ;

>> B = [1; 2; 3];

>> C = [1

2

3];

This creates a row vector called A that contains the values 10, 15, an 20. B is a column vector that looks like

1

2

3

C is the same as B.

More examples:

>> D = [1 2 3; 4 5 6; 7 8 9];

>> E = [1 2 3

4 5 6

7 8 9];

>> F = [1 2 ...

3; 4 5 6;

7 ...

8 9];

This creates the matrix D having 3 rows and 3 columns. It looks like this:

1 2 3

4 5 6

7 8 9

E and F are identical to D. The three dots used in defining F allow us to continue the list of values in a given row on the next line. The semi-colons separate rows. When the three dots are not used the return key also indicates the end of a row. It is important to remember that all rows of a matrix must have the same number of values. Similarly for the columns. It is easy to mistype and leave out a value. If you do that you will get an error message.

Reminder: If we leave the semi-colons off the ends of the commands when entering these definitions, the values of the matrices will be displayed.

Referencing Elements and Sub-matrices: In Matlab the rows and columns are numbered starting with 1 (instead of 0). If A is a matrix, the expression A(i, j) is the element in row i column j of A. Notice that we use parentheses and a comma instead of the pair of square brackets that are used in Java. As in Java (and in mathematics), we always give the row index first and the column index second.

In Matlab we can also easily name a sub-matrix of a given matrix. For example, if A is a 6 by 7 matrix, the command

>> B = A(2:3, 2:6)

defines B to be a matrix with 2 rows and 5 columns. The values in B will be those Contained in rows 2 and 3, in columns 2 through 6 of A.

>> C = A(2:3, : )

defines C to be the matrix containing rows 2 and 3 of A. The use of ‘:’ without any numbers around it indicates that all columns should be included.

Operations on Vectors and Matrices:

Scalar multiplication: If A is a matrix and x is any number, the product x*A is a matrix with the same shape as A in which every element is x times the corresponding element in A. That is, the entry in row i column j of the result equals x*A(i, j).

If two matrices, say A and B, have the same shape we can add them, subtract them, and do other element-by-element operations. The result is a matrix of the same shape. Notice carefully that the last three operations are written using a dot ( "." ) right before the operator symbol. This means that the operation is done element by element. These are not the usual matrix operations of multiplication, division, and exponentiation that some of you are familiar with. For those of you who know about matrices from mathematics, by leaving off the dot you can perform the normal matrix operations.

Symbol Operation

+ addition

- subtraction

.* element-by-element multiplication

./ element-by-element division

.^ element-by-element exponentiation

Example: If A = [1 2 3; 4 5 6], B = [20 30 40; 50 60 70] and C = [0 2 3; 1 3 2], then we get the following.

2*A = [2 4 6; 8 10 12]

A + B = [21 32 43; 54 65 76]

A .* B = [20 60 120; 200 300 420]

A .^ 2 = [1 4 9; 16 25 36]

A .^ C = [1 4 27; 4 125 36]

There are many more built-in operations and functions. See our Matlab syllabus for a few more, including the size and max functions. You can use the help command to learn more about them. Just type in help max, for example. (Don't forget our warning above about the usage of lower and upper case in the help command.)

Changing the Shape of an Array (For more information see Pratap p.47):

The symbol [ ] represents the null matrix. One use of this matrix is for deleting columns, rows, or sub-matrices of a matrix.

Example:

A(2:2, : ) = [ ] removes row 2 from A

So does the command A(2, : ) = [ ]

A(2:4, : ) = [ ] removes rows 2 through 4 from A.

 

We can build a new matrix by combining other matrices or parts of matrices.

Example: If A = [10 20 30; 40 50 60; 70 80 90] and v = [1; 2; 3], then the command

M = [A(1:1, : ); [1 5 9]; A(2:3, :)]

creates matrix M that looks like

 

10 20 30

1 5 9

40 50 60

70 80 90

Notice that M has the first row of A as its row 1. Its second row is the vector [1 5 9]. Its third and fourth rows are the same as rows 2 and 3 of A.

The command N = [ v A] creates the matrix

1 10 20 30

2 40 50 60

3 70 80 90

Some Extra Goodies: There are many useful built-in functions. Some of them are on page 48 of Pratap.

The function ones can be used to create a matrix of all ones.

A = ones(2, 3) creates a 2 by 3 array of 1’s.

Similarly, the function zeros is used to create an array of zeros, and the function rand creates an array of random real numbers between 0 and 1.

The function linespace is used to produce a vector of numbers evenly spaced over a specific range. The command C = linspace(a, b, n) assigns C a vector containing n values evenly spaced between a and b.

For example, the command D = linspace (0, 10, 5) assigns D the vector [ 0 2.5 5 7.5 10 ]

The function sum(v) yields the sum of the elements of v if v is a vector (one row or column). If A is an m by n matrix with more than one row and column, then sum(A) yields a row vector having n columns. The value of each element in the vector is the sum of the elements in the corresponding column of A.

If A is a square matrix, diag(A) is the vector containing the major diagonal of A.

The transpose of a matrix A is the matrix formed by taking the rows of A and making them the columns of the new matrix. If the matrix is square this amounts to flipping the values over the major diagonal. The single quote symbol in Matlab produces the transpose.

Example: If A = [1 2 3] and B = A’ then B is the column vector

[1

2

3]

If A = [1 2 3

4 5 6

7 8 9]

and B = A’ then

B = [1 4 7

2 5 8

3 6 9]

A = A’ changes A to its transpose.

 

 

III. Your Assignment

Part A

Start up Matlab and do the following problems. Just type the appropriate commands in the command window. For each question, do the assignments and calculations in the order in which they are given. Do not type a semi-colon at the end of any lines unless we tell you to do so. That way the values of the variables and matrices you create will be displayed. Type a return at the end of each line.

1. Create variables x and y, assigning them the values 4 and 6, respectively.

Calculate the value of the square root of 2*x + 3*y + y ^ 2 and assign the result to variable z.

Type the name z on a line by itself. (It should display z's value).

Type in the command w = 2; (with the semi-colon this time). It should not display any value with the semi-colon there, although the assignment of 2 to w has been done.

2. Create a row vector v with 4 elements, having the values 3 7 11 9.

Assign variable t the transpose of v.

Calculate the sum of the values in v using the function sum.

Calculate the maximum value in v using the function max.

Create a 3 by 4 matrix A (3 rows and 4 columns) that contains all zeros. Do this by using the zeros function.

Check the size of A by using the size function.

Reassign A a matrix with 4 rows and 3 columns that contains a set of random numbers. Use the rand function to do this.

Again check the size of A.

3. Create a matrix B with 3 rows and 4 columns that has values

3 6 8 4

4 9 10 0

1 -1 10 -3

Create a vector called u that contains the sum of each of the columns of B by using the function sum.

Type in the command help cumsum.

Now create an array C that contains the cumulative sums of each of the columns of B by using the function cumsum. Do you understand what the values in C are? Each element of C is the sum of the values above it in the corresponding column of B.

4. Now try adding rows and columns to B as follows to create arrays with new shapes.

Create an array D that looks like B with an extra row at the bottom containing the values -2 -4 -6 1.

Now create an array E that is the same as B except that it has a new row inserted between the first and second row of B. Give that row the values 2 2 2 2.

Now create an array F that looks like B with a new column on the left side containing the values 1 3 5.

 

 

5. Perform some operations as directed below on the arrays you just created.

Add D and E. (Notice that these matrices have the same shape.)

Square each element of F and store the result back in F.

Multiply each element of D by the corresponding element of E and store the result in matrix G.

Calculate the sum of the elements on the diagonal of D. Use the functions diag and sum to do this.

6. Create a row vector v1 with values 9 5 12 15 2 1 0 3. Assign to v2 the transpose of v1. (Vector v2 should be a column vector.)

Display the sizes of v1 and v2.

7. Use the help command some more: Ask for help on the function ones. Try it again for some other function you want to know more about, e.g. linspace. Now demonstrate that you understand the information given to you by the help command by using the function in some simple example.

8. Write a function with parameters i and A that creates a row vector from the ith row of A and returns the sum of the values in this row (using the function sum). Put the header for the function on the top line. Place a comment stating what the function does (in terms of its parameters) immediately below the header for the function. (Do not put it above the header.) The comment you write here will be displayed by the help command if you ask for help on this function you just wrote.

Write another function that does the same for a column.

Remember that each function must be saved in a separate file and that the file must have the same name as the function. See page 2 of our Matlab Syllabus if you have forgotten the exact format.

Next go back to the command window and use the help command to display the comments you wrote for both of these two functions. Do this by typing help <function name>, where <function name> is replaced by the name you gave your function.

Now create two matrices of different shapes. Illustrate the use of your functions by calling each several times, using both matrices and a few selections of rows and columns.

9. Try drawing a graph. Create a vector x = linspace(0, 20). Draw a graph containing x^2 and another one containing x^3. Draw them on the same axes (so they both appear in one picture), marking one with a dashed line and the other with a solid line (or something else). Remember that the command hold on keeps the current picture in the graphics window from being erased when a second curve is drawn there. Also, plot can plot multiple curves without using the hold on command. Type in help plot to learn more. Also look at the examples on the Matlab syllabus.

10. As a final exercise, play with the logical operations.

Type in the command z = [5, 2, 0, 0] | [0, 3, 0, 1]. z should have been assigned a vector that is all 0's and 1's. Look carefully at it to see where it is 0 and where it is 1.

Do the same thing using & instead of |.

Type in the commands w = [1, 2, 3]; y = [5, 1, 6]; and z = (w > y). Check z's value carefully.

Now type in z = (w < y) and look at z's value again.