02 Matlab Vecters and Matrices

Preview:

DESCRIPTION

Lecture (2): Matlab Vecters and Matrices - Sulaimani University - College of Science - Physics Department

Citation preview

1

Vectors and Matrices

Introduction to Matlab 2

Omed Ghareb AbdullahSulaimani UniversitySulaimani UniversityCollege of SciencesCollege of SciencesPhysics DepartmentPhysics Department

1

Everything in MATLAB is a matrix !

2

2

Array Operations 

[ ] Array constructor[ ] y[ ] Brackets are used to form vectors and matrices.

Example:

A = [ 2 3.5 -5 4 36 7 4 21]

indicate that A is an array of 7 elements also the above can bewritten as

A = [ 2 , 3.5 , -5 , 4 , 36 , 7 , 4 , 21]

separating elements with comma or space, and resulting

2 3.5 -5 4 36 7 4 213

Vectors and MatricesVectors (arrays) are defined as

[1 2 ]>> v = [1, 2, 4, 5]

>> w = [1; 2; 4; 5]

Matrices (2D arrays) defined similarly

>> A = [1,2,3;4,-5,6;5,-6,7]

l 1 2 3

⎥⎥⎥

⎢⎢⎢

−−=

765654321

A Row 1

Row 2

Co

l

Co

l

Co

l

Row 34

3

The Colon (:) Operator

1:10 ==> [1 2 3 4 5 6 7 8 9 10]1:10 > [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10]0:10:50 ==> [0 , 10 , 20 , 30 , 40 , 50]0:pi/4:pi ==> [0 , 0.7854 , 1.5708 , 2.3562 , 3.1416]

5

Long Array, Matrix >> t =1:10

t =t 1 2 3 4 5 6 7 8 9 10

>> k =2:-0.5:-1

k =2 1.5 1 0.5 0 -0.5 -1

>> x = [1:4; 5:8]

x =1 2 3 45 6 7 8

6

4

Creating ArraysA semicolon as punctuation in the square bracket operator tells MATLAB to start a new rowoperator tells MATLAB to start a new row

>> A = [1, 2, 3; 10, 20, 30]

linspace and the colon operator can be used to create vectors that are subsequently composed into an array:

>> A = [1:3:15; linspace(0,1,5)]or…>> A = [(1:3:15)', linspace(0,1,5)']

7

Addition / subtraction of two vectors

>> v1 = [ 1 3 4 ]>> v1 = [ 1, 3, 4 ]>> v2 = [ 2, 5, 3 ]>> v1 + v2

1 2>> v1 – v2mnmnmn BAC ××× +=

ijijij bac +=8

5

Scalar multiplication of a vector

>> v = [ 2 3 4]>> v = [ 2, 3, 4]>> k = 10>> k * v

ans =20 30 40

9

Dot & Cross product

>> u = [2 4 7]>> u = [2 4 7]>> v = [10 20 30] >>w = cross(u, v) >>w = dot(u, v)

vvww

αα

22112121 .),).(,(. yxyxyyxxwv +==

10

6

Indexing using parentheses>> A(2 3)

Matrix Index

>> A(2,3)

Index submatrices using vectorsof row and column indices 

>> A([2 3],[1 2])

Ordering of indices is important!O de g o d ces s po a !>> B=A([3 2],[2 1])

>> B=[A(3,2),A(3,1);A(2,2);A(2,1)]

11

Index complete row or column using the colon operator 

Matrix Index

p>> A(1,:)

Can also add limit index range>> A(1:2,:)

>> A([1 2],:)

General notation for colon operator>> v=1:5

>> w=1:2:5

12

7

⎥⎥⎤

⎢⎢⎡

01986745

Matrix Index

⎥⎥⎥

⎦⎢⎢⎢

=

354718210198

A

How can we extract the collection of numbers in the dotted box?How can we extract the collection of numbers in the dotted box?

That is the numbers in the 1st through 3rd rows 2nd through 4th columnsThat is the numbers in the 1st through 3rd rows 2nd through 4th columnsThat is, the numbers in the 1st through 3rd rows, 2nd through 4th columns…That is, the numbers in the 1st through 3rd rows, 2nd through 4th columns…

Specify the row and column numbers by counting them…Specify the row and column numbers by counting them…

A(1:3, 2:4)A(1:3, 2:4)

13

Matrix IndexThe Matrix in MATLAB

Columns( )

4 10 1 6 2

8 1.2 9 4 25

7.2 5 7 1 11

1 6 11 16 21

2 7 12 17 22

3 8 13 18 23

A =1

2

Rows (m) 3

(n)1 2 3 4 5

A (2,4)

A (17)0 0.5 4 5 56

23 83 13 0 10

4 9 14 19 24

5 10 15 20 25

4

5Rectangular Matrix:

Scalar: 1-by-1 array

Vector: m-by-1 array

1-by-n array

Matrix: m-by-n array14

8

Matrix IndexThe matrix indices begin from 1 (not 0 (as in C))The matrix indices must be positive integer

Given:Given:

A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)

Error: ??? Index exceeds matrix dimensions.15

Concatenation of Matrices>> x = [1 2], y = [3 4], z=[ 0 0]

>> A = [ x y]

1 2 3 4

>> B = [x ; y]

1 23 4

>> A = 1:4A = 1 2 3 4

>> C= repmat(A,3,2)

C = [x y ;z]

Error:??? Error using ==> vertcat CAT arguments dimensions are not consistent.

REPMAT: Replicate and tile an array.

16

9

MATLAB Function Reference  disp: (Description) Display text or array

>>disp(A)>>disp(A)

displays an array, without printing the array name. If Acontains a text, the string is displayed. Another way todisplay an array on the screen is to type its name, but thisprints a leading “A=" which is not always desirable.

>> disp('The Result is'),disp(A)The Result is

1 2 3

4 -5 6

5 -6 7 17

Built‐in Functions and OperatorsThe same types in Vectors exist – with new possibilities

>> D = [5,10, 15; 20,25,30;35,40,45]

>> sumOverColumns = sum(D,1)>>sum(D)

>> sumOverRows = sum(D,2)>>sum(D’)’

Sum of diagonal elements:>> trace(D) 18

10

Built‐in Functions end and sizeCreate an array A by the following:

A [1 2 3 4 10 11 12 13 20 21 22 23]>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]

Replace the last and next to last row/column

elements with [100, 101; 200, 201]

>> A(end-1:end,end-1:end) = [100, 101; 200, 201]

For vectors, we had length to return the number of

elements.

For arrays, size built-in function is used:

>> [numRows, numCols] = size(A)

numRow=3

numCols=4

19

Max &MinLargest component of a matrix A>> (A)>> max(A)

20 21 200 201>> max(A’)’

4101201

>> min(A)>> min(A’)’>> min(A,[],1)>> min(A,[],2)

Smallest component of a matrix A

20

11

Mean & LengthAverage or mean value of a matrix A>> mean(A)

10.3333 11.3333 101.0000 102.0000>> mean(A’)’

2.500055.5000110 5000110.5000

>> length(A)Length of vector: The statement length(A) is equivalent to max(size(A)) for nonempty arrays and 0 for empty arrays.

421

Matrix Multiplication

pmmnpn BAC ××× = ∑=

=m

kkjikij bac

1nnnnnnnn ABBA ×××× ≠

22

12

Matrices Operations

Gi A d BGiven A and B:

Addition Subtraction Product

23

You can delete rows and columns from a matrix using just a pair of square brackets. Start with

Deleting Rows and Columns

>>A = [ 16 3 2 13

5 10 11 8

9 6 7 12

4 15 14 1 ];

Then, to delete the second column of A, use

>>A(:,2) = [ ]

This changes A to:

24

13

Operators (Element by Element).* Element-by-element multiplication./ Element-by-element division.\ Element-by-element left division.^ Element-by-element power

>> a .* b

ans =

0 5 5 2

>> a ./ b

ans =

0 0.2000 5.0000 0.500025

The use of “.” – “Element” OperationA = [1 2 3; 5 1 4; 3 2 1]

A =

1 2 31 2 3

5 1 4

3 2 -1

y = A(3 ,:)

y=

b = x .* y

b=

c = x . / y

c=

d = x .^2

d=

x = A(1,:)

x=

K= x^2

Erorr: ??? Error using ==> ^ Matrix must be square.

B=x*y

Erorr: ??? Error using ==> * Inner matrix dimensions must agree.

y=

3 4 -1

b=

3 8 -3

c=

0.33 0.5 -3

d=

1 4 9

x=

1 2 3

26

14

The Transpose Operator

The transpose operator is used to flip an array.

More formally, if A is an NxMvector, then A' will be an MxNarray whose elements are defined by A'(i,j) = A(j,i).

[ ]642Bh42

BIf

27

15041

A then 2154701

A If

:Examples

T

T

⎥⎤

⎢⎡

⎥⎥⎥

⎢⎢⎢

−=⎥

⎤⎢⎣

⎡ −=

p p p y

y ( j) (j )

The effect of applying the transpose operator to an array is to flip rows and columns.

[ ]

963852741

C then 987654321

C If

642B then 64B If

T

T

⎥⎥⎥

⎢⎢⎢

⎡=

⎥⎥⎥

⎢⎢⎢

⎡=

=⎥⎥⎥

⎦⎢⎢⎢

=

27

The Transpose Operator>> A = [1,2,3,4; 10,11,12,13; 20, 21,22,23]

>> T= A’>> T= A

The effect of applying the transpose operator to an array is to flip rows and columns.

Transponate conjugates complex entries; avoided by>> T=A.’

mnT

nm AT ×× = jiij at =

IfIf AAT = A is symmetricA is symmetric

28

15

Flip Matrix

flip matrix about vertical axes:flip matrix about vertical axes:>> B=fliplr(A)

flip matrix about horizontal axes:>> C=flipud(A)

29

Matrix Left DivisionA linear system of equations can be modeled as:

1523

1023

−=−−=++−

=−+

zyxzyx

zyx

⎥⎥⎥

⎢⎢⎢

−=

⎥⎥⎥

⎢⎢⎢

⎡×⎥⎥⎥

⎢⎢⎢

−−−

15

10

111231123

zyx

In other words…In other words…

yxA vv = yAx vv 1−= yAx vv \=⇒⇒

30

16

Solutions to Systems of Linear EquationsSolution by Matrix Inverse: Solution by left division:

>> a = [ 3 2 -1; -1 3 2; 1 -1 -1];

>> b = [ 10; 5; -1];

>> x = inv(a)*b

x =

-2.0000

5.0000

>> a = [ 3 2 -1; -1 3 2; 1 -1 -1];

>> b = [ 10; 5; -1];

>> x = a\b

x =

-2.0000

5.0000

-6.0000

Answer:x1 = -2, x2 = 5, x3 = -6

-6.0000

NOTE: left division: A\B B ÷ A right division: A/B A ÷ B

Answer:x1 = -2, x2 = 5, x3 = -6

31

The square root of the elements of A:>> As=sqrt(A)

Matrix Functions

The matrix exponential of A:>> As=sqrtm(A)

The exponential of the elements of A:>> As=exp(A)

The principal square root of the matrix A:>> As=expm(A)>> As=expm(A)

The natural logarithm of the elements of A:>> As=log(A)

The matrix logarithm of A:>> As=sqrtm(A)

32

17

Matrix FunctionsMany elementary matrices predefined>> help elmat;

Elementary matricesElementary matrices.

zeros - Zeros array.

ones - Ones array.

eye - Identity matrix.

repmat - Replicate and tile array.

rand - Uniformly distributed random numbers. (0-1)

randn - Normally distributed random numbers.randn Normally distributed random numbers.

linspace - Linearly spaced vector.

logspace - Logarithmically spaced vector.

freqspace - Frequency spacing for frequency response.

meshgrid - X and Y arrays for 3-D plots.

: - Regularly spaced vector and index into matrix.33

Basic array information

Matrix FunctionsMany elementary matrices predefined>> help elmat;

Basic array information.

size - Size of array.

length - Length of vector.

ndims - Number of dimensions.

numel - Number of elements.

disp - Display matrix or text.

isempty - True for empty array.isempty True for empty array.

isequal - True if arrays are numerically equal.

isequalwithequalnans - True if arrays are numerically equal.

isnumeric - True for numeric arrays.

islogical - True for logical array.

logical - Convert numeric values to logical.34

18

Generating Vectors from functionseye(M) MxM matrix of eydentety x = eye(3,3)

x =

eye(M,N) MxN matrix of eydentety

1 0 00 1 00 0 1

x = eye(3,4)x =1 0 0 00 1 0 00 0 1 0

AAIIA == 35

Generating Vectors from functionszeros(M,N) MxN matrix of zeroszeros(M) MxM matrix of zeros

x = zeros(1,3)x =

ones(M,N) MxN matrix of onesones(M) MxM matrix of ones

rand(M N) MxN matrix of uniformly 

0 0 0

x = ones(1,3)x =1 1 1

rand(M,N) MxN matrix of uniformly distributed random       numbers on (0,1)

rand(M,M)    MxM matrix 

x = rand(1,3)x =0.9501 0.2311 0.6068

rand Uniformly distributed random elements

randn Normally distributed random elements36

19

The eigenvalues of the matrix A is .

>> e = eig(A)

Eigenvalues

g( )

e =

34.0000

8.0000

0.0000

-8.0000

One of the eigenvalues is zero, which is another consequence of singularity. The largest eigenvalue is 34,

37

R = rref(A) produces the reduced row echelon form of A using Gauss Jordan elimination with partial pivoting.

Reduced row echelon form

A default tolerance of (max(size(A))*eps *norm(A,inf)) tests for negligible column elements.

>> R=rref(A)

R =

1 0 0 1

0 1 0 -3

0 0 1 3

0 0 0 038

20

DeterminationAA must be squaremust be square

1221221112111211det aaaa

aaaa

aaaa

−==⎥⎦

⎤⎢⎣

The determinant of this particular matrix happens to be zero,

3231

222113

3331

232112

3332

232211

333231

232221

131211

detaaaa

aaaaa

aaaaa

aaaaaaaaaa

+−=⎥⎥⎥

⎢⎢⎢

22212221 aaaa ⎦⎣

The determinant of this particular matrix happens to be zero, indicating that the matrix is singular.

>> d = det(A)

d =

0 39

The determinant of this particular matrix happens to be zero, indicating that the matrix is singular.

Determination

>> d = det(A)

d =

0Since the matrix is singular, it does not have an inverse. If you try to compute the inverse with

>> X = inv(A)

you will get a warning message

Warning: Matrix is close to singular or badly scaled.

Results may be inaccurate. RCOND = 9.796086e-018.40

21

Matrices: Magic Squares

This matrix is called a “magic square”

Interestingly, Durer also datedDurer also dated this engraving by placing 15 and 14 side-by-side in the magic square.

41

The magic FunctionA = magic(3)A =

8 1 6

B = magic(4)B =

16 2 3 13

3 5 7 4 9 2

5 11 10 89 7 6 124 14 15 1

This is called a magic square because the sum of the elements in each column is the same.

>> sum(A)

15 15 15

And the sum of the elements in each row, obtained by transposing twice, is the same.

>> sum(A')' >> sum(A )

15

15

15

This is also a special magic square because the diagonal elements have the same sum.

>> sum(diag(A))

>> sum(diag(fliplr(A)))

15

>> trace(A)

42

22

>> c = [1 2 3; 4 5 6; 7 8 9;...

2 2 2; 3 3 3; 4 4 4]’

>> d = reshape(c, 3,3,2) >> size(d)

3D Matrices

c =

1 4 7 2 3 4

2 5 8 2 3 4

3 6 9 2 3 4

d(:,:,1) =

1 4 7

2 5 8

3 6 9

ans =

3 3 2

3 6 9 2 3 4

>> size ( c)

3 6

d(:,:,2) =

2 3 4

2 3 4

2 3 4

RESHAPE:

Change size

43

3D Matrices

1 0 0 01 0 0 0

0 1 0 0

0 0 1 0

0 0 0 1

Page N0 0 0 0

0 0 0 0

0 0 0 0

0 0 0 0

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

1 1 1 1

1 2 3 4

1 3 6 10

Page 1

1 4 10 20

44

23

Useful Matrix Functions

For complete list, see :

Help MATLAB Help

MathematicsMatrices and Linear Algebra

Function Summary

45

>> x = 0:pi/20: 2*pi;>> y = sin(x);

Graphics

0.8

1

>> plot(x,y,’b-x’); % blue line, x’s>> hold; % keep lines>> z = cos(x);>> plot(x,z,’r:+’); % dotted red, +’s

0 1 2 3 4 5 6 7-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

46

Recommended