You are on page 1of 31

# MH2401 Algorithms & Computing III Slides 3

## August 19, 2013

Recap
Vectors are one dimensional arrays size and length are two ways to know the length of a vector The : (colon) operator creates vectors with regular step size: start : step : end Display of output can be controlled by using ; (semicolon) and disp Mathematical, logical and relational operators are evaluated

## based on their precedence

Control ow statements: ifelseifelse, for, while. They are all terminated with end MATLAB les should end with sux .m MATLAB les can be either scripts or functions, but not both If the MATLAB le consists of functions, only the rst

## Topics for today

Introduce matrices How to access elements of a vector or matrix Arithmetic operations on vectors and matrices Creating some special matrices all-zero, all-one, identity,

diagonal
Constructing new matrices from old Recursive functions

Vectors indexing
Individual elements of a vector can be accessed or extracted

by calling the vector with the index number. The indexing starts from 1, unlike other languages like C or C++.
>> a = 1 0 : 1 0 : 1 0 0 ; >> disp ( a ( 1 ) ) % first element is indexed by 1 10 >> disp ( a ( 1 0 ) ) 100 The vector can be called with an array too! >> disp ( a ( 1 : 3 ) ) % first 3 elements 10 20 30 >> disp ( a ( [ 1 3 5 ] ) ) 10 30 50

Vectors indexing

Last element is accessed by end >> disp ( [ a ( end ) , a ( end 1) ] ) 100 90 You can assign values to particular elements of a vector, but

## both the sides of the equation must have same length

>> a ( [ 3 2 ] ) = [ 2 0 3 0 ] ; % swapping a(2) and a(3) >> disp ( a ) 10 30 20 40 50 60 70 80 90 100 >> a ( [ 3 2 ] ) = a ( [ 2 3 ] ) ; % another way

Vectors indexing
One special case is if the right side has only one number.

## Then all the indexed entries will be set to that number.

>> a ( 2 : 5 ) = 0 ; disp ( a ) 10 0 0 0 80 90 100 0 60 70

## It is possible to assign elements which have indices larger than

the array. MATLAB automatically extends your array or vector, lling the remaining entries with 0
>> a = 1 : 3 ; >> a ( 6 ) = 6 ; % MATLAB automatically extends a >> disp ( a ) 1 2 3 0 0 6

## Vectors logical indexing

In logical indexing you use a logical expression to extract the

elements of the vector. This form of indexing is very useful, very fast, and is probably unique to MATLAB.
>> a = 1 : 1 0 ; >> disp ( a ( a > 5) ) % 6 7 8 >> disp ( a ( mod ( a , 2 ) 2 4 6 What is a>5? >> a > 5 ans = 0 0 0 0 0 1 1 1 1 1 Get 9 == 8 numbers bigger than 5 10 0 ) ) % Get even numbers 10

Each element of the vector a is compared against 5 and it returns a logical vector of 0 and 1, where 0 is false and 1 is true .

## Vectors logical indexing

A logical vector is not a sequence of 0 and 1 numbers. >> a ( [ 1 0 1 ] ) % Error since 0, 1 are numbers To get a logical vector use the logical command. >> L = l o g i c a l ( [ 1 0 1 ] ) ; disp ( L ) 1 0 1 >> disp ( a ( L ) ) 1 3 >> a ( [ t r u e f a l s e t r u e ] ) % this is also OK You can do interesting things such as: >> a ( mod ( a , 2 ) == 0 ) = 0 % set even numbers to 0 a = 1 0 3 0 5 0 7 0 9 0

Vectors transpose
Taking a conjugate transpose of a vector is easy! Use the

operator.
>> a = 1 : 3 ; disp ( a ) % a is a column vector 1 2 3 >> a = [ i , i + 1 ] ; disp ( a ) 0 1.0000 i 1.0000 + 1.0000 i If you want just the transpose, then use the . operator. >> a = [ i , i + 1 ] ; disp ( a . ) 0 + 1.0000 i 1.0000 1.0000 i

Vectors transpose

## Remember when we said everything in MATLAB is an array?

Try and check the output of the following commands. What do you think the output should be?
>> >> >> >> a a a s = 1 . 5 ; disp ( a ) = i ; disp ( a . ) = 1 0 : 1 0 : 1 0 0 ; disp ( size ( a ) ) = a s t r i n g ; disp ( s )

Matrices
Matrices in MATLAB are two dimensional arrays They are input as rows, the rows being separated by ;

(semicolon)
Each row must be of the same length >> M = [ 1 : 3 ; 4 : 6 ; 5 : 7 ; 1 0 : 1 2 ] ; >> disp (M) 1 2 3 4 5 6 5 6 7 10 11 12 >> disp ( size (M) ) % 4 rows , 3 columns 4 3 >> disp ( size (M, 1 ) ) % size along dimension 1 4

Matrices indexing
Matrices can be indexed in two ways. First way is to use pairs of numbers or arrays (r, c), where r denotes the row(s) and c denotes the column(s)
>> M = [ 1 : 3 ; 4 : 6 ; 5 : 7 ] ; disp (M) 1 2 3 4 5 6 5 6 7 >> disp (M( 1 , 2 ) ) % First row , second column 2 >> disp (M( 2 : 3 , 2 ) ) % 2nd & 3rd row , 2nd column 5 6 >> disp (M( 2 : 3 , [ 1 3 ] ) ) % 2nd & 3rd row , 1st & 3rd column 4 6 5 7

Matrices indexing
Matrices can be indexed in two ways. Second way is to index by a number or array n. A matrix in MATLAB has a linear indexing of its entries that proceeds along columns as shown below. Let M be the matrix
>> M = magic ( 3 ) ; >> disp (M) 8 1 6 3 5 7 4 9 2

## Then the index numbers are as follows

1 2 3 4 5 6 7 8 9

Matrices indexing
8 1 6 M = 3 5 7 4 9 2 1 4 7 Index: 2 5 8 3 6 9

>> disp (M( [ 3 4 ] ) ) 4 1 >> disp (M( end ) ) 2 >> M( 5 : end ) = 0 ; disp (M) 8 1 0 3 0 0 4 0 0 >> M( 1 : 3 ) = 1 0 : 1 0 : 3 0 ; disp (M) 10 1 0 20 0 0 30 0 0

Matrices indexing
The colon : operator by itself can be used to denote an entire row or entire column, or the entire matrix if used as a linear index 8 1 6 M = 3 5 7 4 9 2
>> disp (M( 2 , : ) ) 3 5 7 >> disp (M( : , [ 1 3 ] ) ) 8 6 3 7 4 2 >> disp (M( : ) ) % the 8 3 4 1

prints it as a row 5 9 6

## Matrices logical indexing

Logical indexing also works just as in the case of vectors.
>> M = magic ( 3 ) ; >> disp (M(M > 5 ) ) 8 9 6 7 >> disp (M > 5 ) % 1 wherever the comparison is true 1 0 1 0 0 1 0 1 0 >> M(M> 5) = 0 ; disp (M) 0 1 0 3 5 0 4 0 2

Matrices - extending
Just like the case of vectors, matrices will be automatically extended by MATLAB if you assign a value to a nonexisting element. The other remaining elements will be initialized to 0.
>> M = magic ( 3 ) ; >> M( 6 , 6 ) = 1 ; % (6 ,6) MATLAB extends M >> disp (M) 8 1 6 3 5 7 4 9 2 0 0 0 0 0 0 0 0 0 entry doesn t exist , so

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 1

## Matrices Arithmetic operations

Usual mathematical operations work between matrices of

## appropriate dimensions and follow same precedence:

+, , /, , >> M1 = magic ( 3 ) ; M2 = [ 1 : 3 ; 4 : 6 ; 5 : 7 ] ; >> disp ( [ M1M2, M1M2 ] ) 42 57 72 7 1 3 58 73 88 1 0 1 50 65 80 1 3 5 In disp the arrays must have the same size. Hence something like the example below will fail since disp can not combine a

## one dimensional string with a matrix.

>> disp ( [ M1 s q u a r e = , num2str (M1) ] ) % error

## Matrices Arithmetic operations

Solving an equation: \ operator. Given a (column) vector b,

## we want to know the (column) vector x that solves M x = b

>> M1 = magic ( 3 ) ; % M1 is invertible >> M1 \ [ 0 0 0] ans = 0 0 0 This is similar to doing x = inv(M)b. However, the numerical implementation is dierent since the \ operator

doesnt actually compute the inverse and instead performs Gaussian elimination. See doc inv

## Matrices Arithmetic operations

Transpose ( . ) and conjugate transpose ( ) >> A = [ i >> disp (A 0 1i 1 0i >> disp (A. 0 + 1i 1 + 0i 1; 1 i ] ; ) 1 0i 0 + 1 i ) 1 + 0i 0 1 i

## Matrices Elementwise arithmetic operations

Elementwise product . , power . , right divide ./ and left divide .\ >> M = [ 1 : 3 ; 4 : 6 ] ; >> disp (M. M) 1 4 9 16 25 36 >> disp (M. 3 ) 1 8 27 64 125 216 >> disp ( 1 . /M) 1.0000 0.5000 0.2500 0.2000

0.3333 0.1667

## Not surprisingly, it works even for non-square matrices

Operator precedence

See doc precedence for complete list 1. () 2. , ., . , 3. unary + or , logical not 4. , /, ., ./, .\, \ 5. +, 6. : 7. = =, <, >, <=, >=, = 8. && 9. ||

## Some special matrices

Zero matrix matrix with all entries zero zeros(n) creates an n n matrix zeros(n, m) or zeros([n m]) creates an n m matrix One matrix matrix with all entries one ones(n) creates an n n matrix ones(n, m) or ones([n m]) creates an n m matrix Diagonal matrix create a diagonal matrix from a vector. diag(v) creates a diagonal matrix with the entries of the vector v along the diagonal >> disp ( diag ( 1 : 3 ) ) 1 0 0 0 2 0 0 0 3 Identity matrix: eye(n) creates n n identity matrix

Concatenating matrices
Along dimension 1, that is, along rows use semicolon or vertcat . The number of columns must match. >> M1 = [ 1 2 ] ; M2 = [ 3 4 ] ; >> disp ( [ M1 ; M2 ] ) % ; separates rows 1 2 3 4 >> M = v e r t c a t (M1, M2) % same output as above Along dimension 2, that is, along columns separate by spaces, commas or use horzcat . The number of rows must

match.
>> disp ( [ M1 M2 ] ) 1 2 3 4 >> h o r z c a t (M1, M2) % same output as above

We have been using concatenation all the time while using disp!

Concatenating matrices
Use the command cat.
>> M1 = [ 1 2 ] ; M2 = [ 3 4 ] ; >> disp ( c a t ( 1 , M1, M2) ) 1 2 3 4 >> disp ( c a t ( 2 , M1, M2) ) 1 2 3 4 >> M3 = eye ( 2 ) ; >> M = [ [ M1 ; M2 ] , M3 ] ; disp (M) 1 2 1 0 3 4 0 1 >> disp ( c a t ( 2 , M, zeros ( 2 ) , o n e s ( 2 ) ) ) 1 2 1 0 0 0 3 4 0 1 0 0

1 1

1 1

Joining strings
Since strings are just one dimensional arrays of characters, you

can do the same operations on strings, provided that their dimensions match. Concatenate horizontally
>> [ h o r z c a t ( t h i s , string ] ans = is , a ), single

this is a single string Concatenate vertically >> v e r t c a t ( abc , d e f ) % both strings must have same length ans = abc def

Functions
Functions are dened using function keyword
1

function o u t = f u n c t i o n n a m e ( a r g s )

## array. Below we return three values

1

function [ o1 , o2 , o3 ] = f u n c t i o n n a m e ( a r g s )

1 2 3 4 5

## function [ o1 , o2 , o3 ] = g e t s i n c o s t a n ( x ) o1 = sin ( x ) ; o2 = cos ( x ) ; o3 = tan ( x ) ; end >> x = magic ( 3 ) ; >> [ s i n x , c o s x , t a n x ] = g e t s i n c o s t a n ( x ) ;

Functions - recursion
A recursive function is one which calls itself from within its

own body
1 2 3 4 5 6 7 8

function o u t = f n ( n ) if n == 1 % base case to stop recursion o u t = 1 ; return ; e l i f n == 0 % extra case o u t = 1 ; return ; end o u t = n f n ( n 1) ; % calls itself end

Recursive step to compute factorial: n! = n (n 1)! Important! There is a base case which stops the recursion

## The base case is 1! = 1

Functions - recursion

## The factorial can also be written nonrecursively.

1 2 3 4 5 6 7 8 9

function o u t = f n ( n ) if n == 0 o u t = 1 ; return ; end o u t = 1 ; % initialize out for k = 1 : n out = out k ; end end % end of function

Functions - recursion

## mathematical function has some inductive form. Using

- Denition: n! = n (n 1)! - Base: 1! = 1

## prove by induction that n! = n (n 1) 1.

Exercise

1. Test out all the examples given in these slides. Ensure that you understand the main concepts.