430 likes | 729 Views
MatLAB Lesson 2 : Matrix Computation. Edward Cheung email: icec@polyu.edu.hk Room W311g. 2008m. Matrix Manipulation in MatLAB. Array is an orderly grouping of information in computing
E N D
MatLABLesson 2 : Matrix Computation Edward Cheung email: icec@polyu.edu.hk Room W311g 2008m
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,2 2,1] % can use LF to separate rows a = 1 2 2 1
Matrix Indexing >> M M = 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 addressing ans = % count down by left column 3 >> M(8) ans = 13
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
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
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 00 8 9 00 7 6
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 x x = 1 11 21 >> y=M(:,2) % get second column of M into y y = 2 12 22 >> z=M(2,:) % get second row of M into z z = 11 12 13 14 15
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
Addition & Subtraction On Array • Element-by-element operation >> a=[1 2 3]; >> b=[2 5 8] b = 2 5 8 >> a+b ans = 3 7 11 • Both matrices must have the same dimension (element) • If the multiplier is a scalar, for example:- >> ans*9 ans = 27 63 99
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.
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 product ans = 36 >> dot(a,b) % dot product usingthe dot function ans = 36 C = dot(a,b) = sum(a.*b)
Matrix Transpose • Transpose • Changes row to column • In mathematics we wrote AT • in MatLAB we wrote A’ >> a a = 1 2 3 4 5 6 >> a' ans = 1 4 2 5 3 6
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 b ans = 36 >> dot(a,b) ans = 36
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)
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
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
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*v x = 0 4 10 >> B=[8 1 6;3 5 7;4 9 2]; >> u u = 2 3 4 >> y=u*B y = 41 53 41
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 matrix ans = % ans is a matrix (3*3) -4 -6 -8 0 0 0 4 6 8 >> u*v ans = 4 % ans is a scalar
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=0 j=1*0-0*3=0 k=1*4-2*3=-2
Application - Solving Simultaneous Equations • Consider a Linear System with 3 equations & 3 unknowns ax + by + cz =p dx + ey + fz = q gx + hy + iz = r • We can rewrite the system of equations in matrices
Solution using Matrix Multiplications • Write matrix equations:- • 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.
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)*C X = % solution 4.0000 % x -2.0000 % y -2.0000 % z
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.
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
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 1 x(:,:,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
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 usefulmatrix generators:- • One() • Eye() • Rand() • Magic()
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 infinity ans = -2 4 >> floor(d) %rounding towards minus infinity ans = -3 3
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 digits x = 0.0012 >> x=x/10 % a smaller x x = 1.2346e-004 % short show sci. notation >> format short g x = 0.00012346 % show 5 digits >> x=x/10 % a even smaller x x = 1.2346e-005 % show scientific notation >> format short x = 1.2346e-005 % no difference with ‘Best’
Format Hex and hexadecimal operations • >> hex2dec('3b9ac0ff') ans = 999997695 >> a=20; >> format hex >> a a = 4034000000000000 % This is in IEEE-Std-754 floating point % format, not radix-16. >> hex2dec('a') % convert base-16 to base-10 ans = 10
Create Multidimensional Array Example: - To create a 3 pages 3D array from a 3x3 matrix >> m=[1 2 3;4 5 6;7 89] m = 1 2 3 4 5 6 7 8 9 >> size(m) ans = 3 3 >> m(:,:,3)=5 m(:,:,1) = 1 2 3 4 5 6 7 8 9 m(:,:,2) = 0 0 0 0 0 0 0 0 0 m(:,:,3) = 5 5 5 5 5 5 5 5 5 >> size(m) ans = 3 3 3
Magic Square • MAGIC(N) produces a valid N-by-N matrix constructed from the integers1 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) Where M(n) is the Magic Constant
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))
Complex Number > y=complex(1,3) y = 1 + 3i y_real= real(y) % return the real part of y Y_imag=imag(y) % return the imaginary part Mag(y)= abs(y) % return the magnitude of y Angle_y= angle(y) % return the angle of y Conj_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
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)
Random Number Generators • Two different pseudorandom numberfunctions 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
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.
Pseudorandom Sequence Generation • When you start up a new MatLab, you can try:- >>format long >>rand ans = 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.
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 generator e.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 clock e.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)
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
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