143 views

Uploaded by danielck

Advanced Instructions

- WeeklyHomework9_S15
- STPM Sem 1 Mathematics Assignment (Matrice)
- Blue print mathematics class xii
- Matrices and Determinants PDF
- Experimjent 3 Vector Analysis
- R Introduction
- TRANSFORMATION
- fx-991EX_Quick_Reference_Guide.pdf
- table function
- Basic Matlab Guide
- [Non-QU] Linear Algebra by Dr.Gabriel Nagy.pdf
- Maths_XII_2011_12
- Prelim Prac Exam01
- 6442462 Linear Algebra by Jim Hefferon
- MT105b_vle[1]
- Laws of Matrices
- u4.43.03
- MT105B Mathematics 2.pdf
- Scra2012 Eng
- det_prop.pdf

You are on page 1of 10

Lab 2

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

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

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

0

0 ,

2

... .

(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

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)

A(i,:)

A(:,j)

[n m] = size(A)

Built in functions:

dot(X,Y)

cross(X,Y)

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

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.

1

2

B=

9

3

0

2

0

1

0

3

0

0

1

4

.

1

1

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

- WeeklyHomework9_S15Uploaded byprettystargrl
- STPM Sem 1 Mathematics Assignment (Matrice)Uploaded byLai Chungyi
- Blue print mathematics class xiiUploaded byVivek Singh
- Matrices and Determinants PDFUploaded byARANGWALA
- Experimjent 3 Vector AnalysisUploaded byOmar Khan
- R IntroductionUploaded bylamaram32
- TRANSFORMATIONUploaded byBurhan Basit
- fx-991EX_Quick_Reference_Guide.pdfUploaded bySbl
- table functionUploaded byReal Ecuador
- Basic Matlab GuideUploaded bynikita gupta
- [Non-QU] Linear Algebra by Dr.Gabriel Nagy.pdfUploaded byamr
- Maths_XII_2011_12Uploaded byGokul Gj
- Prelim Prac Exam01Uploaded byrroger22
- 6442462 Linear Algebra by Jim HefferonUploaded bybennyb16368
- MT105b_vle[1]Uploaded byklchoudhary
- Laws of MatricesUploaded byRahul Ghadse
- u4.43.03Uploaded bylbo33
- MT105B Mathematics 2.pdfUploaded bymagnifiqueheart
- Scra2012 EngUploaded bySambasivaRao Katuri
- det_prop.pdfUploaded byBarath
- CBSE 12 Mathematics Sample Paper 1Uploaded byAbhishek Kukreti
- 19309board ExaminationUploaded byAnapurna Monga
- Kirch Off Appendix AUploaded byMahir Mahmood
- Report FormatUploaded bychinoi C
- Topic 3.pdfUploaded byAnonymous alwVE8BCQ
- HW09Uploaded byCody Sage
- 33A Syllabus and ScheduleUploaded bythatscribdacnt
- Exagr Mati 1314Uploaded byAna Reis
- Lecture 4Uploaded bymrio2
- MITRES2_002S10_lec06Uploaded byDaniel

- EY Insights on GRC Big DataUploaded byManzar Khan
- Sap Pro Sapiens 201603Uploaded bymona2009pooja
- Deformations in CeramicsUploaded byashutoshgoel
- AP2400-I01 DS 1-0-1Uploaded bysnoopdoggy123
- MANUAL } Jiffy SteamerUploaded byNicholas Sklar
- Smart LPG SystemUploaded byIRJET Journal
- AstronomyUploaded byAkshay Patel
- N852Uploaded byEngTamer
- Beumer Overland Belt Conveyor EnUploaded byIgor San Martín Peñaloza
- Chapter 6-Well Completion.pptUploaded byjorge_h_rivero
- Enron ModbusUploaded byAbhay Soni
- gratisexam.com-Isaca.Braindumps.COBIT-5.v2015-03-30.by.Adelia.50qUploaded bybob
- SEKUploaded bynor_salamiah
- Eventbrite landing pageUploaded byChantal Erbie
- Dahua DMSS Android User ManualUploaded byHaneefa Kalathil
- Buster 5Uploaded byAnonymous GfPSYi4n
- Schneider Et Al-2015-Child Development Perspectives Bibliografie 2015Uploaded byThe Lullaby
- Nef Intermediate SlownictwoUploaded byOut Sider
- U.S.dividendChampionsUploaded byRaghavanJayaraman
- Thermally Upgraded PaperUploaded byamulya00428
- Users GuideUploaded bykhin600
- Preparing CrystalsUploaded byJo Pinto
- Standards Code DirectionsUploaded bydestiny_eastep
- In My Room - Collier ImprovUploaded byJelle Willems
- Lab+Manual+2014 cbe 2207Uploaded byKrishnan Mohan
- Manual Field Servicio Fw740Uploaded byMaria Pia Vera
- Soft Starter Supplied by EAGLE TECHNOLOGY_WGQH Type_Technical DatasheetUploaded byEAGLE TECHNOLOGY
- Marc AugeUploaded byNathan Carter Eastwood
- 1314 OGCDP ICPS Exchange Fact Sheet InsuranceUploaded byTenka
- Centrifuge Rotor Selection and Maintenance 2Uploaded byLike Erlina Sigiro