You are on page 1of 10

Math 152

Lab 2

What to expect from this lab


After completing this lab, you should be able to:
create a matrix using the zeros and ones commands
access and change parts of a matrix
implement for loops
use the det command to calculate the determinant of a matrix.
create and execute m-files

Changing part of a matrix


Suppose A is a MATLAB matrix. We say a matrix is n m if it has n rows and m columns. Consider the
following 3 4 matrix A as an example
>> A = [1
A =
1 2
3 4
5 6

2 1 2; 3 4 3 4; 5 6 5 6]
1 2
3 4
5 6

(Note: whenever we display >> matlabCode, we just mean that inside the Matlab terminal, you type
matlabCode. e.g. to follow along with the above, you would simply type into the terminal A = [1 2 1 2;
3 4 3 4; 5 6 5 6].)
How can we extract pieces of A? Individual entries can be accessed by specifying the row n, counting down
from the top, and column m, counting from the left, in the notation A(n,m). For example
>> A(2,3)
ans =
3
We can change the entry to, say, 7 by entering the command
>> A(2,3) = 7
A =
1 2 1 2
3 4 7 4
5 6 5 6
Notice than when we adjust a component of A and omit the semi-colon at the end of the command, MATLAB
displays the new version of A.
To extract a sub-matrix, we must specify a range of rows and columns. For example, (assuming you have
changed the A(2,3) entry to 7)

>> A(1:2,2:3)
ans =
2 1
4 7
Now lets set all these entries to zero.
>> A(1:2,2:3)=[0 0; 0 0]
A =
1 0 0 2
3 0 0 4
5 6 5 6
By the way, we could have used zeros(2,2) in place of [0 0; 0 0], i.e. used the command
>> A(1:2,2:3) = zeros(2,2)
The function zeros(m,n) is built into MATLAB which creates a m n matrix with all zero entries. A
similar function is ones(m,n), except that ones creates a m n matrix with all unit entries. So if we wanted
to turn the entries of A previously changed to zeros into ones, we could use the command
>> A(1:2,2:3) = ones(2,2)
A =
1 1 1 2
3 1 1 4
5 6 5 6
Remember you can get information about any function in MATLAB, like ones, by typing help ones.
When specifying ranges of rows and columns, we may use end to denote the last row or column. This is handy
if we are not sure how long the matrix is. Also, we can mix the notations for single rows or columns, and
ranges. For example, to extract the first row of A, that is, A(1:1,1:4) we could equally well use A(1,1:end).
Even more succinctly, the range 1:end can simply be specified by :.
>> A(1,:)
ans =
1 1 1 2
This a handy notation if you want to perform operations on a single row or column of a matrix. You may
want to modify this matrix so that the second row is the result of subtracting the first row from the second.
This is achieved by
>> A(2,:) = A(2,:) - A(1,:)
A =
1 1 1 2
2 0 0 2
5 6 5 6
Try it. You may have already learnt in the lectures, or you will soon, that performing operations on the
individual rows of a matrix is a common technique to find the solution of a linear system.

Exercise 1
Let B be the matrix

1
2
B=
9
3

0
2
0
1

0
3
0
0

1
4
.
1
1

Store B into Matlab by typing B = [1 0 0 1; 2 2 3 4; 9 0 0 1; 3 1 0 1]. Denote the i-th row of B


by Ri (i.e., R3 = 9 0 0 1 .).
(a) Give the Matlab code that returns the second row of the matrix B.
(b) Write the Matlab code that replaces the second row R2 of B by the quantity R2 3R4 , i.e., modify B
so that its second row is replaced with the second row minus 3 times the fourth row.
(c) With the modified matrix B following part (b), write down the element of B that is in the fourth column
of the second row.

det command
The command det(A) returns the determinant of a square (same number of rows and columns) matrix A.
You have seen in the lectures how to compute determinants of 2 2 (2 rows and 2 columns) and 3 3
matrices. Later in the course you will see how to calculate determinants of larger, square matrices. This is
implemented in this MATLAB command.

Exercise 2
Let In be the n n identity matrix, so that it has ones along the diagonal and zeros everywhere else. In
Matlab, the command to create In is given by eye(n) (get it?).
(a) Give a formula for the determinant of In as a function of n, e.g., det(In ) = . . . .
(b) Let An be a modification of the matrix In , where we replace
a 2. So,



1 0
1 0
A2 =
, A3 = 0 1
0 2
0 0

the 1 in the last row and last column with

0
0 ,
2

... .

What is the determinant of A8 ? Just give the value.


(c) Let Bn be a modification of An , where we replace the 2 with



1 0
1 0
B2 =
, B3 = 0 1
0 2
0 0

a 2.

0
0 ,
2

... .

Give a formula, in terms of n, for the determinant of Bn . (Use Matlab to check that your formula works!)

for loops
We will use MATLAB to solve linear systems with many equations and unknowns written as augmented
matrices. We will also use MATLAB to multiply by matrices that describe transition probabilities in random
walks. MATLAB can do the computations very easily, but you still have to enter in the entries of the (possibly
very large) matrix. Luckily, many matrices from applications are sparse (mostly zero entries) or have other
structure that makes them easier to construct with the entry, row and column commands described above,
and using for loops described below.
Suppose we want to perform row operations that will result in the entries in the first column of a matrix
being one. This can be done by dividing each row by its first entry (we assume that all these entries are
nonzero). In other words, we want to perform the commands
A(1,:) = A(1,:)/A(1,1)
A(2,:) = A(2,:)/A(2,1)
.
.
A(n,:) = A(n,:)/A(n,1)
Here n is the number of rows in A. We can automate this sequence of commands using a for loop. To have
a definite example to work on define
A=[2 2 3 4; 1 3 1 3; 3 1 1 2]
We would like our code to work with any matrix, so we dont want to assume that the matrix has 3 rows.
So we begin by determining the number of rows and columns of A using the built-in function size. The
command [n m] = size(A) finds out the number of rows and columns that A has and assigns those numbers
to n and m respectively. For example
>> [n,m] = size(A)
n =
3
m =
4
which confirms A has three rows and four columns. Note that the size command does not create a new
matrix, it merely tells us the dimensions of one already created. Now that n is the number of rows of A, the
commands
for i = [1:n]
A(i,:)=A(i,:)/A(i,1)
end
will perform the needed commands. The for loop works like this. The variable i is set equal to the first
element of the vector [1:n] and the commands between the for statement and the end statement (here
there is only one) are executed with that value of i. The end statement is crucial and MATLAB will generate
an error if it is missing.
Once the program reaches the end statement, it loops back, sets i equal to the second element of [1:n]
and executes the command(s) with this value of i. This process is repeated until i has gone through all the
values in [1:n].

Exercise 3
(a) Initialize a matrix A to be a 15 15 matrix consisting of all zeros, i.e., set A = zeros(15,15). Using for
loop(s), modify A so that the (i, j) entry of the matrix is the sum (i + j) of the row number and column
number. So, A(1, 1) = 2, A(2, 1) = A(1, 2) = 3, etc. Give the Matlab code that you used to build the
matrix.
(b) Say you are given a matrix B with n rows. Using for loop(s), give the Matlab code that returns a matrix
C that consists of the rows of B in the opposite order. i.e., if

1 0 0
B0 = 0 1 0 ,
0 0 1
then we have

0
C0 = 0
1

0
1
0

1
0 .
0

Your code should have n inside it somewhere. When figuring out how to get the code working, it may
be helpful to work with a simple matrix (like the B0 above), and then think about how the code changes
for a general matrix B with n rows.

m-files
Often when using MATLAB, you will want to execute the same sequence of commands more than once with
different input parameters. In addition, for long, complicated sequences of commands you want to be able
to easily go back and change commands that you did not enter correctly, without having to re-enter all the
other commands in the sequence. This can be done by storing the commands in an m file. Let illustrate this
with the instructions we just executed when we illustrated for loops. To get started on this type
edit
into the Command Window. This pops open a separate editor window. Type the sequence of commands
that you wish to store into this screen. In our case let us enter the commands used in the previous section
about for loops.

[n m] = size(A)
for i = [1:n]
A(i,:)=A(i,:)/A(i,1)
end
When you are done, click on File SaveAs at the top of the screen. A little window will pop up. Select
Desktop from the icons on the left, and type the filename changeA into the filename dialog box. You have
now saved your file as changeA.m on the Desktop. (If you make changes to the file later on, and want to
save them, click on File Save). Note that the filename you pick should be one word (no spaces).
Now you can execute all the commands in the file changeA.m by typing one single command in the Command
Window. But before you can do that, you need to select the correct working directory where your m file is located. Just above the MATLAB Command Window, on the right end side of the tool bar there is a dialog box
showing z:\ as the Current Directory. Change that to C:\Documents and Settings\username\Desktop.
(you can click on the arrow on the right end side of the dialog box and select the correct directory from the
drop down menu, or alternatively you can click on the three dots button and select the correct directory from
the tree menu). Now you are ready to execute the commands in the file changeA.m. Simply type changeA
in the Command Window. Notice that you dont type the .m. Of course, you have to define the matrix A
first. Try it.
A=[2 3 4; 3 4 5]
changeA

Exercise 4
Create a new Matlab m-file with the name diagonalSquared.m. You will write a script that builds a n n
matrix A that is zero everywhere except along the diagonal, and on the diagonal, the i-th row has entry i2 .
So, if n = 3, then

1 0 0
A = 0 4 0
0 0 9.
The script will have n as a parameter. So, in the first line of diagonalSquared.m, write n=3 (you can change
the value of n later on). Your task is to fill out the rest of the script in order to build the matrix A. You
must use for loops, and your for loops should involve n. If your code is working properly, and your script
is saved in the Current Directory (see instructions previously described), you should be able to examine the
matrix A by typing in the command line
diagonalSquared
A
(a) Give all the code inside your diagonalSquared.m file.



1 2
3 4
is 1 + 4 = 5). What is the trace of the matrix A described above when n = 20? (The Matlab function
trace might be of use to you.)

(b) The trace of a matrix is the sum of all of the diagonal entries of the matrix. (So, the trace of

Recap of MATLAB commands from labs 1 and 2


Commands to create a row vector:
:
The colon operator is used to create row vectors with evenly spaced entries. When no increment is
specified, the components of the vector are spaced by a unit. So 1:5 generates the row vector 1 2 3 4 5.
To obtain non-unit spacing, specify the increment in between colons. So 1:2:5 generates the row vector 1
3 5. Increments can be decimal or negative numbers. Colons can also be used in sequence inside brackets
to create parts of a vector. So A=[1:0.5:2 4:-1:2] generates the vector A=[ 1 1.5 2 4 3 2].
Commands to create a column vector:

When a vector (or a matrix) is followed by a single quote, the output is a vector (or a matrix) in which
each original row has been switched to a column (also known as transpose).
Commands to create a matrix with more than one row:
;
When a semi-colon is used inside brackets, it ends rows. So A=[1:0.5:2; 4:-1:2] generates the 23
matrix
A=
1 1.5 2
4 3 2
zeros(n,m) and ones(n,m)
all zero or all unit entries.

can be used to create matrices with n rows and m columns with respectively

Operations on vectors:
+
matrix addition. A+B adds each component of A to the corresponding component of B. A and B must
have the same size, unless one is a scalar. A scalar can be added to any size matrix.
matrix subtraction. A-B subtracts each component of B from the corresponding component of A. A and
B must have the same size, unless one is a scalar. A scalar can be subtracted from a matrix of any size. *
scalar multiplication. 3*A multiplies each component of A by 3.
Operations on matrices:
det
The command det(A) computes the determinant of the square (same number of rows and columns)
matrix A.
A(i,j)

gives the entry of A in the ith row and the j th column.

A(i,:)

gives the ith row of A.

A(:,j)

gives the j th column of A.

[n m] = size(A)

returns the number of rows n and columns m of the matrix A.

Built in functions:
dot(X,Y)
cross(X,Y)

dot product of vectors X and Y. The output is a scalar.


cross product of vectors X and Y. The output is a vector.

sqrt(X)
computes the square root of X. If X is a vector, the output is a vector whose components are the
square roots of the components of X.
size(X) returns the number of rows and columns of X.
Other useful commands:
for...end loops are described in lab #2.
7

When a semi-colon is added at the end of a command line, it suppresses the output of the result.

clear

clears the values of all variables.

Lab 2 Assignment Questions


You are required to submit a Word Document or PDF for submission. Please include all of your answers
on a single document, that includes your name, student ID, lab section, and instructor, clearly
indicated at the top of the document.
When submitting, please be sure your document ends in .doc, .docx, or .pdf (Word or PDF). The
TAs will only mark those documents that are submitted as a single file in one of these specified formats.

Q1 Let B be the matrix

1
2
B=
9
3

0
2
0
1

0
3
0
0

1
4
.
1
1

Store B into Matlab by typing B = [1 0 0 1; 2 2 3 4; 9 0 0 1; 3 1 0 1]. Denote the i-th row


of B by Ri (i.e., R3 = 9 0 0 1 .).
(a) Give the Matlab code that returns the second row of the matrix B.
(b) Write the Matlab code that replaces the second row R2 of B by the quantity R2 3R4 , i.e., modify
B so that its second row is replaced with the second row minus 3 times the fourth row.
(c) With the modified matrix B following part (b), write down the element of B that is in the fourth
column of the second row.
Q2 Let In be the n n identity matrix, so that it has ones along the diagonal and zeros everywhere else.
In Matlab, the command to create In is given by eye(n) (get it?).
(a) Give a formula for the determinant of In as a function of n, e.g., det(In ) = . . . .
(b) Let An be a modification of the matrix In , where we replace the 1 in the last row and last column
with a 2. So,



1 0 0
1 0
A2 =
, A3 = 0 1 0 , . . . .
0 2
0 0 2
What is the determinant of A8 ?
(c) Let Bn be a modification of An , where we replace the 2 with a 2.



1 0 0
1 0
B2 =
, B3 = 0 1 0 , . . . .
0 2
0 0 2
Give a formula, in terms of n, for the determinant of Bn . (Use Matlab to check that your formula
works!)
Q3 (a) Initialize a matrix A to be a 1515 matrix consisting of all zeros, i.e., set A = zeros(15,15). Using
for loop(s), modify A so that the (i, j) entry of the matrix is the sum (i + j) of the row number and
column number. So, A(1, 1) = 2, A(2, 1) = A(1, 2) = 3, etc. Give the Matlab code that you used to
build the matrix.
(b) Say you are given a matrix B with n rows. Using for loop(s), give the Matlab code that returns a
matrix C that consists of the rows of B in the opposite order. i.e., if

1 0 0
B0 = 0 1 0 ,
0 0 1
9

then we have

0
C0 = 0
1

0
1
0

1
0 .
0

Your code should have n inside it somewhere. When figuring out how to get the code working, it
may be helpful to work with a simple matrix (like the B0 above), and then think about how the
code changes for a general matrix B with n rows.
Q4 Create a new Matlab m-file with the name diagonalSquared.m. You will write a script that builds a
n n matrix A that is zero everywhere except along the diagonal, and on the diagonal, the i-th row has
entry i2 . So, if n = 3, then

1 0 0
A = 0 4 0
0 0 9.
The script will have n as a parameter. So, in the first line of diagonalSquared.m, write n=3 (you can
change the value of n later on). Your task is to fill out the rest of the script in order to build the matrix
A. You must use for loops, and your for loops should involve n. If your code is working properly, and
your script is saved in the Current Directory (see instructions previously described), you should be able
to examine the matrix A by typing in the command line
diagonalSquared
A
(a) Give all the code inside your diagonalSquared.m file.
(b) 
The trace
of a matrix is the sum of all of the diagonal entries of the matrix. (So, the trace of

1 2
is 1 + 4 = 5). What is the trace of the matrix A described above when n = 20? (The
3 4
Matlab function trace might be of use to you.) Just give the value.

10

You might also like