Top Banner
1 The Hong Kong Polytechnic University Industrial Centre MatLAB Lesson 2 : Matrix Computation Edward Cheung email: [email protected] Room W311g 2008m
40

MatLAB Lesson 2 : Matrix Computation

Jan 22, 2016

Download

Documents

Seth

MatLAB Lesson 2 : Matrix Computation. Edward Cheung email: [email protected] Room W311g. 2008m. Matrix Manipulation in MatLAB. Array is an orderly grouping of information in computing - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: MatLAB Lesson 2 : Matrix Computation

1

The Hong Kong Polytechnic UniversityIndustrial Centre

MatLABLesson 2 : Matrix Computation

Edward Cheung

email: [email protected]

Room W311g

2008m

Page 2: MatLAB Lesson 2 : Matrix Computation

2

Matrix Manipulation in MatLAB

• Array is an orderly grouping of information in computing

• Matrix is a rectangular array of numbers like coefficients of linear transformations or systems of linear equations that we can manipulate with Algebra

• The terms array & matrix are often used interchangeably

• Define a Matrix in MatLAB>> a=[1,2;2,1]; % “,” or “ “ separate elements % “;” to separate rows > a=[1,22,1] % can use LF to separate rowsa = 1 2 2 1

Page 3: MatLAB Lesson 2 : Matrix Computation

3

Matrix Indexing

>> MM = 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25>> M(2,2)ans = 12>> M(7) % alternative single index addressingans = % count down by left column 3>> M(8)ans = 13

Page 4: MatLAB Lesson 2 : Matrix Computation

4

Reference a Matrix using keyword “end”M = 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25>> M(1,end)ans = 5>> M(end,end)ans = 25>> M(end)ans = 25>> M(end,1)ans = 21>> M(end,2)ans = 22>> M(2,end-1)ans = 14

Page 5: MatLAB Lesson 2 : Matrix Computation

5

Ellipsis for long assignment statement

• Ellipsis “...” is a set of 3 periods to indicate the row is continue on next line

>> b=[1 2 3 4 5 6 7 ...8 9 0 11 22 33 44]b = Columns 1 through 11 1 2 3 4 5 6 7 8

9 0 11 Columns 12 through 14 22 33 44

Page 6: MatLAB Lesson 2 : Matrix Computation

6

Matrix in Matrix

We can insert an element into the vector.>> c=[21,b] % add first element in b

Suppose we have two 2x2 matrices and would like to form a 4x4 matrices as follows:-

>> a=[1 2;3 4];>> b=[8 9;7 6];>> c=[a zeros(2,2);zeros(2,2) b]c = 1 2 0 0 3 4 0 0 0 0 8 9 0 0 7 6

Page 7: MatLAB Lesson 2 : Matrix Computation

7

Extract Row & Column Matrix with Colon Operator>> M=[1,2,3,4,5;11,12,13,14,15;21,22,23,24,25]M = 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25>> x=M(:,1) % get first column of M into xx = 1 11 21>> y=M(:,2) % get second column of M into yy = 2 12 22>> z=M(2,:) % get second row of M into zz = 11 12 13 14 15

Page 8: MatLAB Lesson 2 : Matrix Computation

8

Extract Matrix from Matrix

• Suppose we want to extract the lower right corner matrix of M and put it into a matrix v

>> v=M(2:3,4:5) v = 14 15 24 25

• Transform matrix into a column matrix using colon operator

> v(:)ans = 14 24 15 25

Page 9: MatLAB Lesson 2 : Matrix Computation

9

Addition & Subtraction On Array

• Element-by-element operation>> a=[1 2 3];>> b=[2 5 8]b = 2 5 8>> a+bans = 3 7 11

• Both matrices must have the same dimension (element)

• If the multiplier is a scalar, for example:->> ans*9ans = 27 63 99

Page 10: MatLAB Lesson 2 : Matrix Computation

10

Dot Product

• The dot product of 2 vectors from Cartesian space is given by

• Dot products are communicative Dot(a,b)=dot(b,a)

• The result is a scalar

• If the dot product is zero, the vectors are orthogonal or perpendicular to each other.

cosBABA

],...,,[ & ],...,,[

...

2121

2211

N

1

NN

NNii

i

bbbaaawhere

babababaC

BA

BA

Page 11: MatLAB Lesson 2 : Matrix Computation

11

Dot Product of Vectors

>> a=[1 2 3]; % 2 vectors a & b>> b=[2 5 8];>> y=a.*b y = 2 10 24>> sum(y) % sum all elements get dot productans = 36>> dot(a,b) % dot product using the dot functionans = 36

ii

iC BA

N

1

C = dot(a,b) = sum(a.*b)

Page 12: MatLAB Lesson 2 : Matrix Computation

12

Matrix Transpose

• Transpose Changes row to column In mathematics we wrote AT in MatLAB we wrote A’

>> aa = 1 2 3 4 5 6>> a'ans = 1 4 2 5 3 6

Page 13: MatLAB Lesson 2 : Matrix Computation

13

Matrix Multiplication

• Using matrix multiplication, the dot product of two column vectors can be written as

>> a=[1 2 3];>> b=[2 5 8];>> a*b‘ % matrix multiplication of a & Transpose % of bans = 36>> dot(a,b)ans = 36

BABA TC

Page 14: MatLAB Lesson 2 : Matrix Computation

14

Some Properties of Matrices

• Two matrices are equal iff both are having the same number of rows and columns and corresponding elements are equal

• Matrix multiplication is the multiplication of rows into columns

• For A(m*n) matrix and B(r*p) matrix, the product AB can only be defined if n=r and the result is m*p matrix (rows and columns must match)

jkk

kii,j ,

N

1,C BA

Page 15: MatLAB Lesson 2 : Matrix Computation

15

Example on Matrix Multiplication

>> a=[1 2;3 4]a = 1 2 3 4>> b=[1 0;0 1]b = 1 0 0 1>> c=a*b % matrix multiplication c = 1 2 3 4

Page 16: MatLAB Lesson 2 : Matrix Computation

16

Properties of Matrix Multiplication

• Matrix multiplication is not commutative AB≠BA % the order of operation will affect the result

• Raising a matrix to power means

• A3 = AAA

• A matrix must be square in order to be multiplied by itself, therefore power can only be taken on square matrix

• When matrices are raised to non-integer powers, the result is a matrix of complex number

• A matrix times its inverse is called the identity matrix (I) AA-1 = I

• If the determinant of a matrix is zero, the matrix is singular and does not have an inverse

Page 17: MatLAB Lesson 2 : Matrix Computation

17

More on Matrix Multiplication

• A matrix can be multiplied on the right by a column vector and on the left by a row vector>> A=[1 1 1 ;1 2 3; 1 3 6];>> v=[-2 0 2]';>> x=A*vx = 0 4 10>> B=[8 1 6;3 5 7;4 9 2];>> uu = 2 3 4>> y=u*By = 41 53 41

Page 18: MatLAB Lesson 2 : Matrix Computation

18

Vector Products

• A row vector and a column vector of the same length can be multiplier in either order

• The result is either a scaler–the inner product (dot product)• Or a matrix – the outer product (tensor product)

>> u=[2 3 4]; % dimension m-by-n (3*1)>> v=[-2 0 2]‘; % dimension p-by-q (1*3)>> v*u % gives a mp-by-nq matrixans = % ans is a matrix (3*3) -4 -6 -8 0 0 0 4 6 8>> u*vans = 4 % ans is a scalar

Page 19: MatLAB Lesson 2 : Matrix Computation

19

Cross Product of Two Vectors

• Distinguish between cross product and the « vector products »

• Example>> va=[1 2 0];>> vb=[3 4 0];>> cross(va,vb)ans = 0 0 -2

i=2*0-0*4=0j=1*0-0*3=0k=1*4-2*3=-2

Page 20: MatLAB Lesson 2 : Matrix Computation

20

Application - Solving Simultaneous Equations

• Consider a Linear System with 3 equations & 3 unknownsax + by + cz =p

dx + ey + fz = q

gx + hy + iz = r

• We can rewrite the system of equations in matrices

ihg

fed

cba

A

r

q

p

C

z

y

x

X

Page 21: MatLAB Lesson 2 : Matrix Computation

21

Solution using Matrix Multiplications

CAX

CAXAA

CXA

1

11

• If the inverse matrix exist, we can get the solution for X

• In MatLab, Y=inv(A) returns the inverse of the square matrix A

• This method is good for algebra but poor for computation.

•Write matrix equations:-

Page 22: MatLAB Lesson 2 : Matrix Computation

22

Example

To solve: x+y+z=0

x-2y+2z=4

x+2y-z=2

>> A=[1 1 1;1 -2 2;1 2 -1]>> C=[0 4 2]';>> X=inv(A)*CX = % solution 4.0000 % x -2.0000 % y -2.0000 % z

Page 23: MatLAB Lesson 2 : Matrix Computation

23

Matrix Algebra in MatLAB

• In MatLAB, function for matrix operation are abundant

> help matfun Matrix functions - numerical linear algebra. Matrix analysis. Linear equations. Eigenvalues and singular values. Matrix functions. Factorization utilities.

Page 24: MatLAB Lesson 2 : Matrix Computation

24

Selected Functions for Matrices

• sum() - sum of array elements• max() - maximum elements of an array• min() - minimum elements of an array• prod() - product of array elements• cumsum() – cumulative sum of elements• cumprod() – cumulative product of elements• size() - array dimensions• length() – length of vector• sort() – sort elements in ascending order

• Check them out using >>help• Check out the functions on p.17 of the training manual

Page 25: MatLAB Lesson 2 : Matrix Computation

25

Use Size to obtain Dimension of Matrix>> x=ones(4,3,2)x(:,:,1) = 1 1 1 1 1 1 1 1 1 1 1 1x(:,:,2) = 1 1 1 1 1 1 1 1 1 1 1 1>> size(x)ans = 4 3 2

% Noted that MatLab will return (1 1) if the variable is a scaler

Page 26: MatLAB Lesson 2 : Matrix Computation

26

More Matrices Functions

• Empty matrices A matrix having at least one dimension equal to zero>> b=[] % generates the simplest empty matrix 0-by-0 in size.

>> A=zeros(0,5) A = Empty matrix: 0-by-5>>b=0:-1 % also generates an empty matrix

• The following are useful matrix generators:- One() Eye() Rand() Magic()

Page 27: MatLAB Lesson 2 : Matrix Computation

27

Selected Functions on Round Off

>> d=[-2.6 3.1]d = -2.6000 3.1000>> round (d)ans = -3 3>> fix (d)ans = -2 3>> ceil(d) %rounding towards infinityans = -2 4>> floor(d) %rounding towards minus infinityans = -3 3

Page 28: MatLAB Lesson 2 : Matrix Computation

28

An Example on Format “Short” & “Short Good”

• FORMAT SHORT G Best of fixed or floating point format with 5 digits.>> x=0.00123456789; >> format short g % show 5 significant digits x=0.0012346 >> format short % show 5 digitsx = 0.0012>> x=x/10 % a smaller xx = 1.2346e-004 % short show sci. notation>> format short gx = 0.00012346 % show 5 digits>> x=x/10 % a even smaller xx = 1.2346e-005 % show scientific notation>> format shortx = 1.2346e-005 % no difference with ‘Best’

Page 29: MatLAB Lesson 2 : Matrix Computation

29

Format Hex and hexadecimal operations

• >> hex2dec('3b9ac0ff')ans = 999997695>> a=20;>> format hex>> aa = 4034000000000000

% This is in IEEE-Std-754 floating point % format, not radix-16.

>> hex2dec('a') % convert base-16 to base-10ans = 10

Page 30: MatLAB Lesson 2 : Matrix Computation

30

Create Multidimensional Array

>> m=[1 2 3;4 5 6;7 8 9]m = 1 2 3 4 5 6 7 8 9>> size(m)ans = 3 3

>> m(:,:,3)=5m(:,:,1) = 1 2 3 4 5 6 7 8 9m(:,:,2) = 0 0 0 0 0 0 0 0 0m(:,:,3) = 5 5 5 5 5 5 5 5 5>> size(m)ans = 3 3 3

Example: - To create a 3 pages 3D array from a 3x3 matrix

Page 31: MatLAB Lesson 2 : Matrix Computation

31

Magic Square

• MAGIC(N) produces a valid N-by-N matrix constructed from the integers 1 through N2 with equal row, column, and diagonal sums for all N>0 except N=2. This kind of matrix is called Magic Square. 3x3 Magic Square first appears in Lu Shu ( 洛書 )

洛書口訣:「戴九履一、左三右七、二四為肩、六八為足、五居中央。」

>> H=[4 9 2;3 5 7;8 1 6]H = 4 9 2 3 5 7 8 1 6>> magic(3)

2

3 nnnM

Where M(n) is the Magic Constant

Page 32: MatLAB Lesson 2 : Matrix Computation

32

Rearrange the row or column of a matrix

• 洛書口訣:「戴九履一、左三右七、二四為肩、六八為足、五居中央。」

• We can use the following command to the Lo Shu matrix

>> magic(3);>> ans([3 2 1],:)

OR>> flipud(magic(3))

Page 33: MatLAB Lesson 2 : Matrix Computation

33

Complex Number

> y=complex(1,3)y = 1 + 3iy_real= real(y) % return the real part of yY_imag=imag(y) % return the imaginary partMag(y)= abs(y) % return the magnitude of yAngle_y= angle(y) % return the angle of yConj_y= conj(y) % return the complex conjugate of y

Note that if y is a vector, abs(y) gives a vector of absolute value and not magnitude y

Page 34: MatLAB Lesson 2 : Matrix Computation

34

Example

>> y=complex(1,2)y = 1.0000 + 2.0000i>> conj(y)ans = 1.0000 - 2.0000i>> real(y)ans = 1>> imag(y)ans = 2>> abs(y)ans = 2.2361 % verify (1^2+2^2)^.5>> angle(y)ans = 1.1071 % verify atan(2/1)

Page 35: MatLAB Lesson 2 : Matrix Computation

35

Random Number Generators

• Two different pseudorandom number functions are available:- Uniform random numbers

• Generate evenly distributed number range 0 to 1

• All values within a given interval are equally probable

• Generate double-precision numbers in interval [2^(-53), 1-2^(-53)]

• Theoretically can generate over 2^1492 values before repeating itself

Gaussian random numbers• The values near the mean are more likely to occur

• Mean = 0, variance =1

Page 36: MatLAB Lesson 2 : Matrix Computation

36

Different Default Algorithms in MatLab

• Different algorithms can be used to generate pseudorandom numbers in MatLab. In MatLab Ver.5 to 7.3, method ‘state’ refers to a modified version of subtract with borrow algorithm from Marsaglia & Zaman in 1991, a well tested and widely use algorithm.

• In MatLab version 7.4, a new default method called ‘twister’ is used. This is based on the Mersenne Twister algorithm by Makoto Matsumoto & Takuji Nishimura in (1996-2001). This method generates double-precision numbers in the closed interval [2^(-53), 1-2^(-53)] with a period of (2^19937-1)/2

• In version 4, method ‘seed’ was the default which generates double precision numbers in the closed interval [1/(2^31-1), 1-1/(2^-31-1)] with a period of 2^31-2.

Page 37: MatLAB Lesson 2 : Matrix Computation

37

Pseudorandom Sequence Generation

• When you start up a new MatLab, you can try:->>format long>>randans = 0.95012928514718 % MatLab 7.3 0.814723686393179 % MatLab 7.4

• This “random” number comes up every time under the same startup condition.

• Computer is a deterministic machine, without external factor or device such as noise generator, it cannot generate a true random number.

Page 38: MatLAB Lesson 2 : Matrix Computation

38

Uniformly Distributed Random Number

• rand(n) – returns an n x n matrix• rand(m,n) – returns an m x n matrix, elements range 0 to 1• rand(‘state’) – returns a 35 element vector containing the

current state of the uniformly distributed generatore.g.>> current_state=rand('state');

• rand(‘state’,x) – x= scalar or any number (0=initial state) x= 35 x 1 state vector

• rand(‘state’, sum(100*clock)) – set the state of the number generator according to system clocke.g.>> rand('state',sum(100*clock))

• randperm(n) – generates a random permutation of integers from 1 to n; function will call rand()e.g.>> dice=randperm(6)

Page 39: MatLAB Lesson 2 : Matrix Computation

39

Random Number Scaling

• Scale up the random number Rand_Num=(max-min)*O_Rand_Num+min

e.g. Generate an uniformly distributed array in the interval [10,20] and check the mean>> y=10*rand(1,1000)+10;mean(y)ans = 15.005

Page 40: MatLAB Lesson 2 : Matrix Computation

40

Generate Normally Distributed Random Number

• Same as ‘rand()’ but the name of function is ‘randn()’ Examples:-

>>randn(n) – returns an n x n matrix, elements =0, s =1

>>randn(m,n) – m x n matrix

• Use y=*x+ for scaling y= new random number x= old random number with =0, =1 =mean of the new random number =standard deviation of new random number

e.g. generate a 1000 elements normally distributed random vector with mean of 15 and standard deviation of 3>> y=3*randn(1,1000)+15>>mean(y);std(y) % checking