MATLAB Tutorial

You need a small numb er of basic commands to start using MATLAB This short tutorial

describ es those fundamental commands You need to create vectors and matrices to change

operate with them Those are all short highlevel commands b ecause MATLAB them and to

constantly works with matrices I b elieve that you will like the p ower that this software gives

by a series of short instructions to do

create E create u change E multiply E u

E eye E E u v E u

2 3 2 3 2 3 2 3

4 5 4 5 4 5 4 5

The word eye stands for the identity The submatrix u E picks out column

E resets the entry to The command E u multiplies the The instruction

u All these commands are rep eated in our list b elow Here is an example matrices E and

inverting a matrix and solving a linear system of

create A create b invert A solve Ax b

A C invA x Anb or A ones eye b

x C b

2 3 2 3 2 3 2 3

4 5 4 5 4 5 4 5

The matrix of all ones was added to eye and b is its third column Then invA pro duces

inverse matrix normally in decimals for fractions use format rat The system Ax b the

solved by x invA b which is the slow way The backslash command x Anb uses is

never computes the inverse matrix When the right if A is square and

0

A the solution x must b e The symbol side b equals the third column of

vector Then A x picks out the third column of A and we have Ax b makes x a column

Here are a few comments The comment symb ol is

The symb ols a and A are dierent MATLAB is casesensitive

Typ e help slash for a description of how to use the backslash symb ol The word help

b e followed by a MATLAB symb ol or command name or Mle name can

Note The command name is upp er case in the description given by help but must b e

lower case in actual use And the backslash Anb is dierent when A is not square

To display all digits typ e format long The normal format short gives digits after

the decimal

after a command avoids display of the result A semicolon

display the A ones will not

uparrow cursor to return to previous commands Use the

How to input a row or column vector

u has one row with three comp onents a matrix

rows separated by semicolons a matrix v has three

0 0

v or v u transposes u to pro duce the same v

w generates the row vector w with unit steps

takes steps of to give u u

How to input a matrix a row at a time

A has two rows always a semicolon b etween rows

A also pro duces the matrix A but is harder to typ e

0 T 0

B is the transpose of A Thus A is A in MATLAB

How to create sp ecial matrices

diagv pro duces the with vector v on its diagonal

to eplitzv gives the symmetric constantdiagonal matrix with v as rst row and rst col

umn

to eplitzw v gives the constantdiagonal matrix with w as rst column and v as rst row

onesn gives an n n

zerosn gives an n n matrix of zeros

eyen gives the n n identity matrix

randn gives an n n matrix with random entries b etween and uniform distribution

randnn gives an n n matrix with normally distributed entries mean and variance

onesm n zerosm n randm n give m n matrices

onessizeA zerossizeA eyesizeA give matrices of the same shap e as A

How to change entries in a given matrix A

A resets the entry to equal

A v resets the third row to equal v

A w resets the second column to equal w

The colon symb ol stands for al l all columns or all rows

A A exchanges rows and of A

How to create submatrices of an m � n matrix A

Ai j returns the i j entry of the matrix A matrix

Ai returns the ith row of A as row vector

A j returns the j th column of A as column vector

A returns rows from to and columns from to as matrix

A returns rows and and all columns as n matrix

A returns one long column formed from the columns of A mn matrix

triuA sets all entries b elow the main diagonal to zero upp er triangular

trilA sets all entries ab ove the main diagonal to zero lower triangular

Matrix multiplication and inversion

A B gives the matrix pro duct AB if A can multiply B

A B gives the entrybyentry pro duct if sizeA sizeB

;1

invA gives A if A is square and invertible

pinvA gives the pseudoinverse of A

AnB gives inv A B if invA exists backslash is left division

Anb gives the solution to Ax b if invA exists x

See help slash when A is a rectangular matrix

Numb ers and matrices asso ciated with A

detA is the if A is a

A is the rank numb er of pivots of row space and of column space

sizeA is the pair of numb ers m n

A is the trace sum of diagonal entries sum of eigenvalues

nullA is a matrix whose n r columns are an orthogonal for the nullspace of A

orthA is a matrix whose r columns are an orthogonal basis for the column space of A

Examples

E eye E creates a elementary elimination matrix

A subtracts times row of A from row E

A b creates the with b as extra column B

eye P E creates a p ermutation matrix E

triuA trilA diagdiagA equals A Note that

Builtin Mles for matrix factorizations all imp ortant

L U P luA gives three matrices with P A LU

e eig A is a vector containing the eigenvalues of A

S E eig A gives a diagonal eigenvalue matrix E and eigenvector matrix S with AS

S E If A is not diagonalizable to o few eigenvectors then S is not invertible

Q R qrA gives an m m Q and m n triangular R with A QR

Creating Mles

Mles are text les ending with m which MATLAB uses for functions and scripts A script

which may b e executed often and can b e placed in an mle so is a sequence of commands

do not have to b e retyp ed MATLABs demos are examples of these scripts the commands

house Most of MATLABs functions are actually mles An example is the demo called

viewed by writing type xxx where xxx is the name of the function and can b e

To write your own scripts or functions you have to create a new text le with any name

you like provided it ends with m so MATLAB will recognize it Text les can b e created

saved with any text editor like emacs EZ or vi A script le is simply a list of edited and

MATLAB commands When the le name is typ ed at the MATLAB prompt the contents of

le will b e executed For an mle to b e a function it must start with the word function the

followed by the output variables in brackets the function name and the input variables

Examples

function CmultA

rrankA

0

A A C

Save the ab ove commands into a text le named multm Then this funtion will take a

pro duct C The variable r is not returned b ecause it matrix A and return only the matrix

was not included as an output variable The commands are followed by so that they will

printed to the MATLAB window every time they are executed It is useful when not b e

dealing with large matrices Here is another example

function VDrpropertiesA

rank eigenvalues and eigenvectors of A This function nds the

mnsizeA

if mn

VDeigA

rrankA

else

dispError The matrix must be square

end

Here the function takes the matrix A as input and only returns two matrices and the rank

comment The function checks to see if the input ma as output The is used as a

trix is square and then nds the rank eigenvalues and eigenvectors of a matrix A Typing

propertiesA only returns the rst output V the matrix of eigenvectors You must typ e

VDrpropertiesA to get all three outputs

Keeping a diary of your work

The command diaryle tells MATLAB to record everything done in the MATLAB

window and save the results in the text le named le Typing diary on or diary o

b e viewed using a text editor or printed using lpr toggles the recording Old diary les can

MATLAB they can b e viewed using the typ e le command in unix In

Saving your variables and matrices

The command diary saves the commands you typ ed as well as MATLABs output but it

do es not save the content of your variables and matrices These variables can b e listed by

which also lists the sizes of the matrices The command save xxx the command whos

save the matrices and all variables listed by the whos command into the le named will

xxx MATLAB lab els these les with a mat extension instead of m which are scripts or

by MATLAB at a later time by typing load xxx functions xxxmat les can b e read

Graphics

The simplest command is plotx y which uses two vectors x and y of the same length The

will ints x y b e plotted and connected by solid lines p o

i i

If no vector x is given MATLAB assumes that xi i Then ploty has equal spacing

xaxis the p oints are i y i on the

The typ e and color of the b etween p oints can b e changed by a third argument The

with no argument is a solid black line Use help plot for many options we indi default

cate only a few

0 0

MATLAB plotx y r plots in r red with for p oints and dotted line

0 0 0 0

MATLAB plotx y is a dashed line and plotx y is a dotted line

You can omit the lines and plot only the discrete p oints in dierent ways

0 0 0 0 0 0 0 0

plotx y o gives circles Other options are or or

For two graphs on the same axes use plotx y X Y Replace plot by loglog or

change one or b oth axes to logarithmic scale The command semilogy or semilogx to

axis a b c d will scale the graph to lie in the rectangle a x b c y d To title the

lab el the xaxis or the y axis put the desired lab el in quotes as in these examples graph or

title height of satellite xlabel time in seconds y label height in meters

The command hold keeps the current graph as you plot a new graph Rep eating hold

To print or save the graphics window in a le see help print or use will clear the screen

print Pprintername print d lename

MIT OpenCourseWare http://ocw.mit.edu

18.06 Linear Algebra Spring 2010

For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.