70
CPS118 – Lesson #4 – Creating Arrays Slide #1 Arrays: Vectors and Matrices Lesson #4

Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

  • Upload
    others

  • View
    14

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Creating ArraysSlide #1

Arrays: Vectors and Matrices

Lesson #4

Page 2: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #2

The array is MATLAB's basic data structure.

• It can have any number of dimensions. Most common are:

The vector : one dimension (a single row or column)

The matrix : two or more dimensions (we will stop at 2).

What Are Arrays?

Page 3: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #3

To create a row vector from known numbers, just type a variable name, then the equal sign, then inside square brackets, the numbers separated by spaces

or commas.

variable_name = [ n1, n2, n3 ]

>> yr = [1984 1986 1988 1990 1992 1994 1996]

yr =

1984 1986 1988 1990 1992 1994 1996

Note: MATLAB displays a row vector horizontally

Commas are optional

Creating a row vector

Page 4: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #4

To create a column vector from known numbers you can use one of two methods:

• Method 1 : same as row vector but put semicolon after all but the last number

variable_name = [n1; n2; n3]

>> yr = [1984; 1986; 1988]

yr =

1984

1986

1988

Note: MATLAB displays a column vector vertically

Creating a Column Vector

Page 5: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #5

• Method 2 : same as row vector but put an apostrophe (') after the closing bracket.

The apostrophe interchanges rows and columns. We will come back on this later.

variable_name = [ n1 n2 n3 ]'

>> yr = [1984 1986 1988 ]'

yr =

1984

1986

1988

Creating a column vector

Page 6: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #6

To create a vector with specified constant spacing between elements, use the m:q:n command. MATLAB will create the vector automatically with the required number of elements. variable_name = m:q:n

m is the first numbern is the last numberq is the difference between consecutive numbers

v = m:q:n means

v = [ m m+q m+2q m+3q ... n ]

Constant spacing vectors

Page 7: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #7

If q is omitted, the spacing is 1

v = m:nmeans

v = [ m m+1 m+2 m+3 ... n ]

>> x = 1:2:13

x = 1 3 5 7 9 11 13

>> y = 1.5:0.1:2.1

y = 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 2.1000

Non-integer spacing

Constant spacing vectors

Page 8: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #8

>> z = -3:7

z = -3 -2 -1 0 1 2 3 4 5 6 7

>> xa = 21:-3:6

xa = 21 18 15 12 9 6

>> fred = 7:-2:15

fred = Empty matrix: 1-by-0

Negative spacing

Constant spacing vectors

Impossible spacing!!!

Page 9: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #9

To create a vector with a specific number of terms between the first and the last, we use the linspace command. MATLAB will take care of the spacing.

v = linspace(xi, xf, n)

• xi is the first number

• xf is the last number

• n is the number of terms (obviously must be a positive number) (100 is used if omitted)

Fixed length vectors

Page 10: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #10

>> va = linspace(0, 8, 6)

va = 0 1.6000 3.2000 4.8000 6.4000 8.0000

>> va = linspace(30, 10, 11)

va = 30 28 26 24 22 20 18 16 14 12 10

m:q:n lets you directly specify spacing. linspace() lets you directly specify the number of terms.

Six elements

Decreasing elements

T I P

Page 11: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #11

1. How would you use linspace to set up spacings for planting seedlets in a garden row (30 seedlets, each row 2 meters long).

2. Plan a 4285 km (Toronto to Los Angeles) road trip taking 21 days. How far would you travel each day?

Quick linspace Exercises

Page 12: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #12

You can create a two-dimensional matrix like this: m = [ row 1 numbers; row 2 numbers; ... ; last row numbers ]

Each row is separated by a semicolon. All rows must have the same number of columns.

>> a = [5 35 43; 4 76 81; 21 32 40]

a =

5 35 43

4 76 81

21 32 40

Matrices

Page 13: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #13

You can use expressions to build matrices.>> cd=6; e=3; h=4;

>> Mat=[e, cd*h, cos(pi/3);... h^2 sqrt(h*h/cd) 14]

Mat =

3.0000 24.0000 0.5000

16.0000 1.6330 14.0000

Commas are optional

Matrices

Page 14: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #14

You can also use m:p:n or linspace() to make rows.

• Make sure each row has the same number of columns!

>> A=[1:2:11; 0:5:25;... linspace(10,60,6); 67 2 43 68 4 13]

A =

1 3 5 7 9 11

0 5 10 15 20 25

10 20 30 40 50 60

67 2 43 68 4 13

Matrices

Page 15: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #15

What if the number of columns is different? You get an error!

>> B= [1:4; linspace(1,4,5)]

??? Error using ==> vertcat

CAT arguments dimensions are not consistent.

Four columns Five columns

Matrices

Page 16: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #16

zeros(m,n) - makes a matrix of m rows and n columns, all with zeros.

ones(m,n) - makes a matrix of m rows and n columns, all with ones.

eye(n) - makes a square matrix of n rows and columns. Main diagonal (upper left to lower right) has ones, all other elements are zero.

Special Matrix Commands

Page 17: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #17

>> zr=zeros(3,4)

zr = 0 0 0 0

0 0 0 0

0 0 0 0

>> ne=ones(4,3)

ne = 1 1 1

1 1 1

1 1 1

1 1 1

>> idn=eye(5)

idn = 1 0 0 0 0

0 1 0 0 0

0 0 1 0 0

0 0 0 1 0

0 0 0 0 1

Page 18: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #18

To make a matrix flled with a particular number, multiply ones(m,n) by that number

>> z=100*ones(3,4)

z =

100 100 100 100

100 100 100 100

100 100 100 100

T I P

Page 19: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #5 – Mathematical Operations with ArraysSlide #19

Filling Arrays with Random Numbers

You can also fill vectors and matrices with random numbers.

MATLAB has three commands that create random numbers : rand, randi, and randn.

All can create scalars, vectors, or matrices of random numbers

Page 20: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #5 – Mathematical Operations with ArraysSlide #20

The rand command

rand generates random numbers uniformly distributed between 0 and 1

• To get numbers between a and b (inclusive), multiply the output of rand by b-a and add a. (b-a)*rand + a

• Use a=1 and b=6 to roll a die!

A row vector 1x10

Page 21: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #5 – Mathematical Operations with ArraysSlide #21

The randi command

randi generates uniformly distributed random integers in a specified range

For example, to make a 3×4 matrix of random numbers between 50 and 90

>> d = randi([50 90],3,4)

d =

57 82 71 75

66 52 67 61

84 66 76 67

Page 22: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #5 – Mathematical Operations with ArraysSlide #22

The randn command

randn generates random numbers from a normal (bell curve) distribution with mean 0 and standard deviation 1.

Page 23: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #23

➢ You can transpose a variable (vector or matrix) by putting a single quote after its name, like x'

• Transposing a row vector changes it to a column vector and vice-versa.

• It switches rows and columns of a matrix: the first row of the original becomes the first column of the transposed, the second row of the original becomes the second column of the transposed, and so on and so forth...

The Transpose Operator

Page 24: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #24

>> aa=[3 8 1]

aa = 3 8 1

>> bb = aa'

bb = 3

8

1

Vector Transpose

bb is aa transposed

Page 25: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #25

>> C = [2 55 14 8; 21 5 32 11; 41 64 9 1]

C = 2 55 14 8

21 5 32 11

41 64 9 1

>> D = C'

D = 2 21 41

55 5 64

14 32 9

8 11 1

Matrix Transpose

See the columns becoming rows and the rows becoming columns!

Page 26: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #26

We can access (extract) elements or groups of elements in a vector or a matrix.

• It is useful for changing an element or a subset of elements.

• It is useful for making a new variable from an element or a subset of elements.

Accessing Elements

Page 27: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #27

Accessing Vector Elements You can access any element by indexing the

vector name with parentheses (indexing starts from 1, not from 0 as in other programming languages like C).

>> vector1 = [1:3:10]

vector1 = 1 4 7 10

>> vector1(3)

ans = 7

Accesses the third element of the vector vector1

Page 28: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #28

We can also access a range of elements (a subset of the original vector) by using the colon operator and giving a starting and ending index.

>> vector1(2:4)

ans = 4 7 10

Simple arithmetic between scalars and vectors is possible.

>> 10 + [1 2 3] ans = 11 12 13

Accessing Ranges of Elements

Get the elements between positions 2 and 4 inclusive from the vector vector1

Remember we did that with the ones matrix?

Page 29: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #29

Addition or subtraction of vectors is possible as long as they are the same size ([10, 11] + [1, 2, 3] would not work!).

>> [1 2 3] + [4 5 6]

ans = 5 7 9

>> x = [1 2 3] - [4 5 6]

x = -3 -3 -3

These operations are called elementwise operations or element-by-element operations. It means that the operations are done in parallel for every element of the vectors. That’s the reason why the sizes must be identical.

Adding and Subtracting Vectors

Page 30: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #30

Element-by-element multiplication and division uses the .* and ./ operators. The * and / operators are used for complete matrix multiplication and division which we will not cover in detail in this class as it requires knowledge of linear algebra. The power operator ^ also requires the dot (.^) for element-by-element.

>> [1 2 3] .* [4 5 6]

ans = 4 10 18

>> [6 5 80] ./ [2 2 2]

ans = 3.0000 2.5000 40.0000

>> [1 2 3] .^ [2 3 4]

ans = 1 8 81

Dividing and Multiplying Vectors

Page 31: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #31

The * operator without the dot is used for linear algrbra operations. For this class, you do not need to know how to do those without MATLAB (this is not a math course) but you should definitely know the difference between . And .* Now let’s have a look at three examples.

Example 1: The * between two vectors is called the scalar product. The first vector must be a row vector, the second one a column vector. Both must have the same number of elements.

v1 = [1 2 3 4]; v2 = [5;6;7;8]; sp = v1 * v2;sp = 70

The * Operator

Page 32: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #32

Example 2: The * between a vector and a matrix. The vector must be a column vector and have the same number of elements as the number of columns in the matrix. In this example both have 4.

m1 = [2 2 2 2 ; 3 3 3 3]; v2 = [5;6;7;8]; mv = m1 * v2mv = 52 78

The * Operator

Page 33: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #33

Example 3: The * between two matrices. This is full fledged matrix multiplication. The number of columns in the first matrix must must be the same as the number of rows in the second matrix. In this example both have 3.

m2 = [2 2 2 ; 3 3 3]; m3 = [5 5 5 5 ; 4 4 4 4 ; 6 6 6 6]; mm = m2 * m3mv = 30 30 30 30 45 45 45 45

The * Operator

Page 34: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #34

Element-by-element can also be applied on matrices. Again, the sizes must be identical.

>> [1 2 3 ; 4 5 6] + [0 1 2 ; 6 4 3]

ans = 1 3 5 10 9 9

>> [1 2 3 ; 4 5 6] - [0 1 2 ; 6 4 3]

ans = 1 1 1 -2 1 3

>> [1 2 3 ; 4 5 6] .* [0 1 2 ; 6 4 3]

ans = 0 2 6 24 20 18

Elementwise Operations on Matrices

>> [4 6 6 ; 2 2 2 ; 1 1 1] ./ [1 1 1 ; 2 2 2 ; 1 1 1] ans = 4 6 6 1 1 1 1 1 1

>> [1 2 ; 3 4] .^ [2 2 ; 3 3] ans = 1 4 27 64

Page 35: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #35

Creating Matrices from Vectors You can create new matrices or new vectors by sticking

vectors together. Of course the sizes must be compatible in some cases.

>> v1 = [1 2 3 4];

>> v2 = [5 6 7 8];

>> m1 = [v1 ; v2]

m1 = 1 2 3 4

5 6 7 8

>> m2 = [v2 ; v1]

m2 = 5 6 7 8

1 2 3 4

>> m3 = [v1 ; v1]m1 = 1 2 3 4 1 2 3 4

>> v3 = [v1 , v2]v3 = 1 2 3 4 5 6 7 8

Page 36: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #36

Appending to Vectors• You can only append row vectors to row vectors

and column vectors to column vectors.

If r1 and r2 are any row vectors, r3 = [r1 r2] is a row vector whose left part is r1 and right part is r2

If c1 and c2 are any column vectors, c3 = [c1; c2] is a column vector whose top part is c1 and bottom part is c2

Page 37: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #37

>> v1 = [3 8 1 24];

>> v2 = 4:3:16;

>> v3 = [v1 v2]

v3 = 3 8 1 24 4 7 10 13 16

>> v4 = [v1'; v2']

v4 = 3

8

1

24

4

7

10

13

16

Appending to vectors examples

You understand

what’s going on here?

Page 38: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #38

Creating Matrices from Matrices You can create new matrices

from other matrices. Be careful about the sizes here!

>> mat1 = [1 2 ; 3 4]

mat 1 = 1 2

3 4

>> mat2 = [mat1 ; mat1]

mat2 = 1 2 3 4 1 2

3 4

>> mat3 = [1 2 3 ; 4 5 6];

>> mat4 = [mat1 , mat3] mat2 = 1 2 1 2 3 3 4 4 5 5 >> mat5 = [mat1 ; mat3] ERROR!

Page 39: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #39

Appending to Matrices

• If appending one matrix to the right side of another matrix, both must have same number of rows.

• If appending one matrix to the bottom of another matrix, both must have same number of columns

Page 40: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #40

>> A2=[1 2 3; 4 5 6]

A2 = 1 2 3

4 5 6

>> B2=[7 8; 9 10]

B2 = 7 8

9 10

>> C2=eye(3)

C2 = 1 0 0

0 1 0

0 0 1

>> Z=[A2 B2]

Z = 1 2 3 7 8

4 5 6 9 10

>> Z=[A2; C2]

Z = 1 2 3

4 5 6

1 0 0

0 1 0

0 0 1

>> Z=[A2; B2]

??? Error using ==> vertcatCAT arguments dimensions are not consistent.

Appending to Matrices Examples

Page 41: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #41

Trig Commands and Arrays When the argument of a trig function is

an array, you get an array of the same size for an answer. It is the same for all other math functions as well, like sqrt.

Ex:

>> sin ([pi/4 pi/2 pi])

ans = 0.7071 1.0000 0.0000

Page 42: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #42

Saving and Loading Variables Use save to save variables to a file at any time you

wish while using MATLAB..

>> save myfile mat1 mat2

saves matrices mat1 and mat2 to the file named myfile.mat

To load saved variables back into the workspace, use load.

>> load myfile

You can write myfile.mat but if you don’t the .mat is assumed.

Page 43: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #43

Index vs. Subscript You remember that indexes are a way to access elements.

Remember that indexes start at 1 in MATLAB. Now let’s do that with matrices. For a matrix you can access an element using an index or a pair of subscripts.

For matrices, subscripts have the row and column numbers separated by a comma. Indexes, on the other hand, indicate the linear position from the start of the matrix. See the figure below for the difference.

subscripts indexes

Page 44: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #44

Matrix Indexing The index argument can be a matrix. In this

case, each element is looked up individually, and returned as a matrix of the same size as the index matrix.

>> a = [10 20 30 40 50 60];

>> b = a([1 2 3 ; 4 5 6])

b = 10 20 30

40 50 60

This is a matrix of indexes. Get it?

Page 45: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #45

Working Whole Rows or Columns The colon operator can select entire rows or columns

of a matrix.

>> c = b (1,:)

c = 10 20 30

>> d = b (:,2)

d = 20 50

>> b (:, 3) = [100 200]

b = 10 20 100

40 50 200

b = 10 20 30 40 50 60

Page 46: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #46

The colon operator : lets you address a range of elements:

• Vector (row or column)

va(:) - all the elements of the vector

va(m:n) – only elements in positions m through n inclusive

• Matrix

A(:,n) - all the rows of column n

A(m,:) - all the columns of row m

A(:,m:n) - all the rows of columns m through n

A(m:n,:) - all the columns of rows m through n

A(m:n,p:q) - columns p through q of rows m through n

Colon Operator

Page 47: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #47

You can replace vector index or matrix indices by vectors in order to pick out specific elements. For example, for vector v and matrix m

• v([a b c:d]) returns elements a, b, and c through d

• m([a b],[c:d e]) returns columns c through d and column e of rows a and b

Getting Specific Columns

Page 48: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #48

>> v = 4:3:34

V = 4 7 10 13 16 19 22 25 28 31 34

>> u = v([3, 5, 7:10])

u = 10 16 22 25 28 31

>> u = v([3 5 7:10])

u = 10 16 22 25 28 31

Colon Operations on Vectors

Page 49: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #49

>> A = [10:-1:4; ones(1,7); 2:2:14; zeros(1,7)]

A = 10 9 8 7 6 5 4

1 1 1 1 1 1 1

2 4 6 8 10 12 14

0 0 0 0 0 0 0

>> B = A([1 3],[1 3 5:7])

B = 10 8 6 5 4

2 6 10 12 14

Colon Operations on Matrices

Page 50: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #50

•Add elements to existing variablesAdding values to ends of variables:

Adding to ends of variables is called appending or concatenating. Use the keyword end as index to get to the end.

The end of a vector is the right side of a row vector or bottom of a column vector.

The end of a matrix is the right column of the bottom row.

That is, MATLAB expands arrays to include indices, puts the specified values in the assigned elements, fills any unassigned new elements with zeros. See next slide.

Page 51: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #51

Assigning to Undefined Indices of Vectors

>> v1 = 1:4

v1 = 1 2 3 4

>> v1(5:10) = 10:5:35

v1 = 1 2 3 4 10 15 20 25 30 35

>> v2 = [5 7 2]

v2 = 5 7 2

>> v2(8) = 4

v2 = 5 7 2 0 0 0 0 4

>> v3(5) = 24

v3 = 0 0 0 0 24

New elements added

Unassigned elements are initialized at zero

Page 52: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #52

To delete elements in a vector or a matrix, set the index, subscript, or range to be deleted to empty brackets.

>> kt=[2 8 40 65 3 55 23 15 75 80]

kt = 2 8 40 65 3 55 23 15 75 80

>> kt(6)=[]

kt = 2 8 40 65 3 23 15 75 80

>> kt(3:6)=[]

kt = 2 8 15 75 80

55 is gone!

Remove elements 3 through 6 of the current kt, not the original kt

Deleting Elements in a Vector or a Matrix

Remove the 6th element of kt

Page 53: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #53

>> mtr = [5 78 4 24 9; 4 0 36 60 12; 56 13 5 89 3]

mtr = 5 78 4 24 9

4 0 36 60 12

56 13 5 89 3

>> mtr(:,2:4)=[]

mtr = 5 9

4 12

56 3

Delete all the rows for columns 2 to 4

Another Removing Example

Page 54: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #54

Finding Minimum and Maximum Values

>> vec = [10 7 8 13 11 29];

To get the minimum value and its index:

>> [minVal,minInd] = min(vec)

minVal = 7 minInd = 2

To get the maximum value and its index:

>> [maxVal,maxInd] = max(vec)

maxVal = 29 maxInd = 6

>> [a,b] = max(vec)

a = 29 b = 6 You can use any variable name you want

Only one variable you get the value only, not the position. x = min (vec)x = 7y = max (vec)y = 29

Page 55: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #55

Finding Minimum and Maximum Values

>> M = [10 20 ; 30 40];

With entire matrices it works column by column. The index is the row.

>> [minVal,minInd] = min(M)

minVal = 10 20

minInd = 1 1

>> [maxVal,maxInd] = max(M)

maxVal = 30 40

maxInd = 2 2

Only one variable you get the values only, not positions. a = min (M)a = 10 20b = max (M)b = 30 40

Page 56: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #56

MATLAB has many built-in functions for working with arrays. Some common ones are:

• length(v) : gives the number of elements in a vector.

• size(A) : gives the number of rows and columns in a matrix or a vector.

• reshape(A,m,n) : changes the number of rows and columns of a matrix or vector while keeping the total number of elements the same. For example, you can change a 4x4 matrix into a 2x8 matrix.

Matrix Built-In Functions

Page 57: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #57

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

>> a = [a , [5 6 ; 7 8]]a = 1 2 5 6 3 4 7 8

>> reshape (a, 1, 8)ans = 1 3 2 4 5 7 6 8

>> reshape (a, 8, 1)

ans = 1 3 2 4 5 7 6 8

reshape Example

Page 58: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #58

• diag(v) : makes a square matrix of zeroes with the specified vector in the main diagonal.

v1 = [33 66 99]; m1 = diag (v1)m1 = 33 0 0 0 66 0 0 0 99

• diag(A) : creates a vector equal to the main diagonal of the specified matrix.

m2 = [42 89 ; 78 31]; v2 = diag (m2)v2 = 42 31

The diag commandOn a vector:

On a matrix:

Page 59: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #5 – Mathematical Operations with ArraysSlide #59

More Built-In Functions for Arrays

• mean(v): calculates the mean (average) of the specified vector.v3 = [45 13 65 62]; average = mean (v3)average = 46.2500

sum(v): gives the sum (total) of all the elements of the specified vector.v3 = [45 13 65 62]; total = sum (v3)total = 185

sort(v): sorts the elements in the specified vector in ascending order.v3 = [45 13 65 62]; v4 = sort (v3)v4 = 13 45 62 65

Page 60: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #60

A string is an array of characters

Strings have many uses in MATLAB

• Display text output

• Specify formatting for plots

• Input arguments for some functions

• Text input from user or data files

Strings

Page 61: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #61

• We create a string by typing characters within single quotes (').

• Many programming languages use the quotation mark (") for strings. Not MATLAB!

•Strings can contain letters, digits, symbols, spaces. Can be words, sentences, anything you want!

•Examples of strings: 'Boston', '4522', '{Canada1867!}', 'Life is good.'

Creating Strings

This is a string, not a number!

Page 62: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #62

You can assign string to a variable, just like numbers.

>> province = 'Ontario'

province =

Ontario

>> park = 'Canada''s Wonderland'

park =

Canada's Wonderland

To have the ' character, you double it.

Page 63: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #63

In a string variable

• Numbers are stored as an array

• A one-line string is a row vectorNumber of elements in vector is number of

characters in string

>> place = 'Niagara Falls';

>> size(place)

ans =

1 13

Page 64: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #64

Strings are indexed the same way as vectors and matrices

• Can read by index

• Can write by index

• Can delete by index

String Indexes

Ex: >>word(1) = 'd';

>>word(2) = 'a';

>>word(3) = 'l';

>>word(4) = 'e';

>>word

word = dale

Page 65: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #65

Example:

>> word(1)

ans = d

>> word(1) = 'v'

word = vale

>> word(end) = []

word = val

>> word(end+1:end+3) = 'ley'

word = valley

word variable is ‘dale’ from previous slide.

First letter is now v

Last letter is gone

ley added at the position following the end and the two other positions after that

Page 66: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #66

MATLAB stores strings with multiple lines as an array. This means each line must have the same number of columns (characters).

>> names = ['Greg'; 'John']

names =

Greg

John

>> size( names )

ans =

2 4

Page 67: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #67

Problem

>> names = [ 'Greg'; 'Jon' ]??? Error using ==> vertcat

CAT arguments dimensions are not consistent.

Must put in extra characters (usually spaces) by hand so that all rows have same number of characters

>> names = [ 'Greg'; 'Jon ' ]

Greg

Jon

3 characters4 characters

Extra space

vertcat means vertical concatenation

Page 68: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #68

Making sure each line of text has the same number of characters is a big pain. MATLAB solves problem with char function, which pads each line on the right with enough spaces so that all lines have the same number of characters.

>> question = char('Romeo, Romeo,','Wherefore art thou', 'Romeo?')question =

Romeo, Romeo,

Wherefore art thou

Romeo?

>> size (question)ans =

3 18

String Padding

Page 69: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #69

Three lines of text stored in a 3x18 array.

MATLAB makes all rows as long as longest row.

First and third rows above have enough space characters added on ends to make each row 18 characters long.

R o m e o , R o m e o ,

W h e r e f o r e a r t t h o u

R o m e o ?

Page 70: Arrays: Vectors and Matrices - Ryerson Universitycps118/slides/04_Arrays.pdf · 2018. 9. 25. · CPS118 – Lesson #4 – Arrays: Vectors and Matrices Slide #30 Element-by-element

CPS118 – Lesson #4 – Arrays: Vectors and MatricesSlide #70

End of lesson