Lab 1

From CSE100B Wiki

Jump to: navigation, search

Lecture slides

Contents

Vectors, Matrices, and Indexing

MATLAB stands for Matrix Laboratory, thus, the main focus and strength of MATLAB involves manipulating matrices. In this lab you will learn how to create matrices and access their elements. Let's get started.

Creating Sequences

Sequences are created using the colon (":") operator. For example, a row vector counting from 1 to 5 can be created with the command:

>> r = 1:5

r =

1  2  3  4  5

We can also specify the interval which can be negative (the default interval is 1):

>>r = 2:-2:-8

r =

2  0  -2  -4  -6  -8
Q1: What is the last entry in the vector created by:
>> r = 0:0.2:1.3

Creating Matrices

Matrices are created using the square brackets ("[]"). Here's a simple matrix, with 3 columns and 1 row:

>> m = [1 2 4]

m =

1  2  4

This example shows how the space character is used for horizontal concatenation ("putting things next to each other"). Multiple spaces are treated as one.

The comma character also serves for horizontal concatenation ([1  2   4]==[1,2,4]), but mutiple commas result in an error.

Vertical concatenation ("putting things on top of each other") is done using the semicolon (";"):

>> m = [1;2;4]

m =

1
2
4

Combining the space/comma and the semicolon, we can create 2D matrices:

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

m =

1 2 3
4 5 6
7 8 9

Here are some equivalent forms:

>> m = [[1 2 3]; [4 5 6]; [7 8 9]] % create three row vectors, and vertically-concatenate them
>> m = [[1; 4; 7] [2; 5; 8] [3; 6; 9]] % create three column vectors, and horizontally-concatenate them
>> m = [[[1 2; 4 5] [3; 6]]; [7 8 9]] % Start with 2x2. Append column vector (now 2x3). Append row vector (now 3x3)
>> x = [1 2; 4 5]
>> m = [[x [3; 6]]; [7 8 9]] % We can build matrices from existing matrices.

Note: The percent character ("%") causes everything following it on the same line to be ignored. This is called a comment. Use comments to explain pieces of code and document your scripts.

lab1_1.m: (The work for this deliverable should be stored in a script named lab1_1.m)
  1. Create a row vector A equal to 1 2 3 4 5 6 7 8 9
  2. Create a row vector B equal to 1 2 3 4 5 6 7 8 9 0 using row vector A
  3. Create the matrix C equal to
    1 2 3 4 5 6 7 8 9 0
    0 1 2 3 4 5 6 7 8 9
    using B and A.

Accessing Matrix Elements

Matrices are accessed using the round brackets ("()"), by specifying the desired row and column indices. To access an element that is in the i'th row and j'th column of matrix M, write M(i,j).

Note: Index in Matlab starts from 1 instead of 0, unlike some other programming languages.

REMEMBER: FIRST ROW, THEN COLUMN!

So, if we have the variable:

rc =
11 12 13
21 22 23
31 32 33

To address the entry in the third row, second column (32) use rc(3,2).

Q2: The following matrix represents the cash values (in millions of dollars) of safety deposit boxes arranged in a grid:

depoboxes = [1 2 5; 4 8 99; 7 6 3]

If you could open one deposit box with the command depoboxes(i,j), what should i and j be to maximize your haul?

lab1_2.m:
  1. Create the following two matrices
    u =
    0     0    0
    0     0    0
    0     0    0
    0     0    0
    0     0    0
    0     0    0
    0     0  299
    0     0    0
    0     0    0
    and
    v =
    0 0 0 0   0 0 0
    0 0 0 0 199 0 0
    Each element in u and v denotes the number of gold coins in a deposit box in vaults u and v.
  2. Create two new variables (numGoldCoinsU and numGoldCoinsV) that contain the value of the treasures in u and v.
    Hint: In each vault, there's only one deposit box that contains gold coins. Since you know the content of each box in both vaults, use indices to retrieve the value of the treasures.
  3. The following command
    >> lab1_2
    should only show the values of numGoldCoinsU and numGoldCoinsV.
Q3: After running lab1_2.m, what does
>> [i, j] = find (v == numGoldCoinsV)

return? (Hint: Remember the help command.)

Q4: After running lab1_2.m, what does

>> index = find (u == numGoldCoinsU)

return?

Using Vectors to Access Vectors

Suppose we have a row vector of size 5:

a = [92   83   74   65   0]

and we want to create a row vector of size 2, that contains only the second and fourth elements (in this case, b = [83  65]).

We already know one way to do it.

Since the second element is a(2), and the fourth element is a(4), then:

b = [a(2) , a(4)]

b =

83    65

MATLAB allows us to use vectors as indices:

b = a([2 4])

If we wanted the first three elements (c = [92   83  54]), we could write:

c = a([1 2 3])

but we already know how to use the colon operator to create sequence (in this case [1 2 3]), so we can write:

c = a(1:3)
Q5: With the vector a defined above, what command returns [0 65 74]? (Hint: Remember negative intervals.)

Using The Colon Operator to Access Matrices

To access several elements of a matrix at a time, use the colon operator like this:

C(1,2:5)

which returns the elements of matrix C in the first row, columns 2 through 5.

Q6: What does this return? What does a colon (":") do in this instance?

>> lab1_1
>> C(:,10)

The colon is an important operator and you will use it often. Be sure you understand it!!

Word Search

Let's play a word search game.

lab1_3.m:
  1. First, load the word search data to your workspace.
    Here's how:
    1. Download lab1_wordSearch.mat to your current Matlab directory.
    2. Load it into the Matlab workspace (type "load lab1_wordsearch").
    or
    1. Download lab1_wordSearch.mat to your desktop.
    2. Drag it into the Command Window. Observe that the load command for accomplishing the same is displayed.
    Observe that the Workspace now contains a matrix of characters named wordSearch.
    10 11 12 13 14 15 16 17
    1 S M O H I T R E A S U R E Q Y Z A
    2 I A B I L M W O R K S P A C E A D
    3 P T E O M E C N I L M A P O D E L
    4 J L E U A S O E D I T O R A R S M
    5 R A D V T C L F T N G E Q Y Z A I
    6 A B U W R R O S O H I B N J E U O
    7 R P C X I I N T U K A R S O P C X
    8 R T U K X P L M R D V F T N G U F
    9 A U N B R T A V E C T O R I N W S
    10 Y O H M F I L E I Q Y Z A I B I L
    11 M A D P E O E N I L M A P O D E L
    12 J E U A R S M R D V F T N G E Q Y
    13 Z A I U W S O H I B N J E U O P C
    14 X T U K A R S O P C X T U K L M R
    15 D V F T N G U F U N B R A I N W S
    16 O H I Q Y Z A I B I L M A D P E O
    17 E N I L M A P O D E L J E U A R S
  2. Include the load command in your script.
  3. Write statements that display at least 5 hidden words from the wordSearch matrix using the colon operator. At least two words should come from rows and at least two words should come from columns. None of the words are backwards or are on diagonals.
    Hidden words: (word search generated by funbrain.com)
    • MATLAB
    • COLON
    • SCRIPT
    • MFILE
    • MATRIX
    • ARRAY
    • VECTOR
    • WORKSPACE
    • EDITOR
    • TREASURE
    You can find the words by looking at the whole matrix or you can display single rows/columns of the matrix. If you want to flip the matrix, swapping rows for columns, put a single quote (') after it. This is the transpose operator. When you find a word, figure out the position of the word, and add a line to your script that prints it out.

Using The Colon Operator to Update Matrices

Recall the matrix in Q2

depoboxes = [1 2 5; 4 8 99; 7 6 3]

After the money has been stolen from the deposit box, the bank must update the cash value.

To do this, the bank executes:

>> depoboxes(2,3) = 0

The owners of deposit boxes in row 3 have decided to move their money to another bank.

To do this, the bank executes:

>> depoboxes(3,:) = 0

Q7: The bank has gone under. What command zeroes-out all of the deposit boxes?

Indexing 2D Matrices with a Single Number

There is a way to index elements in a matrix with a single number (recall Q4). MATLAB uses column-major indexing. The following matrix has values corresponding to their column-major index, i.e., G(1) = 1, G(4) = 4, etc.

G =
1 4 7
2 5 8
3 6 9
Q8: The bank has been bailed out by the government and the original values have been returned. The bank keeps the keys to the boxes hanging on the wall in column-major order. (Look at the original depoboxes matrix and not G to answer these questions.) If the thief takes the fifth key, what is her pay-off? What key should the thief take to maximize her pay-off?

When you are ready, demonstrate your answers to Q1-Q8 and lab1_1.m, lab1_2.m, and lab1_3.m to the TA or instructor and answer some questions to checkout.

Student Questions and Answers

Questions? Please post them on the Google Group http://groups.google.com/group/wustl-matlab.

Personal tools