72
Arrays – Part 2

Arrays – Part 2

  • Upload
    dermot

  • View
    33

  • Download
    0

Embed Size (px)

DESCRIPTION

Arrays – Part 2. 2. Creating vectors. There are LOTS of ways to create vectors, based on three simple ideas: The values in the vector are pre-defined . For example: [ 2 -5 4.4 -96.6] The values have an addition pattern . For example: - PowerPoint PPT Presentation

Citation preview

Page 1: Arrays – Part 2

Arrays – Part 2

Page 2: Arrays – Part 2

2. Creating vectors

• There are LOTS of ways to create vectors, based on three simple ideas:

– The values in the vector are pre-defined. For example: [ 2 -5 4.4 -96.6]

– The values have an addition pattern. For example: [10, 20, 30 ,…100] or [-10 -8 -6 -4 -2 0]

– Or even, the total number of values is known! For example: 25 points evenly spaced from 0 to 100.

Page 3: Arrays – Part 2

2.2. Patterns (addition only)

• For addition pattern, no need to code a lot!

The range operator

Numbers are separated by +1

Page 4: Arrays – Part 2

2.2. Patterns, cont.

• Add an increment to increase by a different amount than +1

An additional value in the middle specifies the increment (aka step-size).

+3 +3 +3 +3 +3 +3 +3 +3 >32

Page 5: Arrays – Part 2

2.2. Patterns, cont.

• Create a decreasing pattern by using a negative increment! CAUTION: the beginning number must be > the end number. Here 10>3.

Note: it works with fractional values.

-2.5 -2.5 -2.5 < 3

Page 6: Arrays – Part 2

2.3. Specific amount of data points

• Sometimes, the increment isn’t so important (or known) vs. HOW MANY points there are.

• A built-in function called linspace() spaces elements linearly in an array.– What does this mean?

• The distance between consecutive data points is a constant across the array.

Page 7: Arrays – Part 2

>>doc linspace <enter>

linspaceGenerate linearly spaced vectors

Syntaxy = linspace(a,b)y = linspace(a,b,n)

DescriptionThe linspace function generates linearly spaced vectors. It is similar to the colon operator ":", but gives direct control over the number of points.y = linspace(a,b) generates a row vector y of 100 points linearly spaced between and including a and b.y = linspace(a,b,n) generates a row vector y of n points linearly spaced between and including a and b. For n < 2, linspace returns b.

Page 8: Arrays – Part 2

2.3. linspace(), cont.

• MATLAB runs out of space to display?

When MATLAB cannot display all the elements on one line, it simply indicates the column numbers for each line.

Page 9: Arrays – Part 2

2.3. linspace(), cont.

• Transpose the return value of linspace() to create a column vector

Page 10: Arrays – Part 2

2.3. linspace(), cont.

?????? %no third argument

Omit the third argument uses a default of _______ data points!

Page 11: Arrays – Part 2

3. Creating Matrices

• Simply a combination of all operators introduced with vectors!– Square brackets [ ]– Spaces or commas , ,– Semi-colons ;– Apostrophes ‘

• Just keep in mind:only RECTANGULAR matrices

Page 12: Arrays – Part 2

3.1. Matrices: hard-coding

• Use semi-colons to create new rows.

• Good or bad? Why?

2 by 3 3 by 2

Page 13: Arrays – Part 2

3.2. Concatenating matrices

• Assume variable a from the previous slide. Use it as a reference to create a new variable:

“CONCATENATING”The art of “gluing”

vectors and matrices together

Page 14: Arrays – Part 2

3.3 Using colons

• Combine ALL methods necessaryJUST KEEP THE ARRAY RECTANGULAR

Page 15: Arrays – Part 2

Array Math

Page 16: Arrays – Part 2

16

I. Definition• MATLAB is known for its mathematical power!

– It does vector and MATRIX operations automatically (most languages require you to do this by hand).

– It follows the rules of ANY math book

• Rules of addition and subtraction are straightforward and highly common sense: think MATH

• Rules of multiplication and division require basic knowledge of matrix math

WikipediaThis is an “n-by-p” matrix. n rows, p columns.

Page 17: Arrays – Part 2

17

II. addition/subtraction (example1)

• Assume the vectors (actual math vectors) shown here

>>v1+v2+v3 <enter> results in?v1 =

2 -3

v2 =

4 -2

v3 =

-1 4

ans =

2 4 -1 -3 -2 4

ans =

5 -1

(a) (b)

Page 18: Arrays – Part 2

18

II. addition/subtraction (example2)

• Assume the matrices A and B below.

>>A+B <enter> results in?

A =

2 0 -3 3 -3 4 -2 2 -1 -3 2 1

B =

8 5 7 4 6 10 9 12 10 5 11 10

ans =

10 5 4 7 3 14 7 14 9 2 13 11

ans =

2 0 -3 3 8 5 7 4 -3 4 -2 2 6 10 9 12 -1 -3 2 1 10 5 11 10

(a) (b)

Page 19: Arrays – Part 2

II. addition/subtraction (example3)

• Assume the matrices A and B below.

>>A+B <enter> results in?

??? Error using ==> +Matrix dimensions must agree.

A =

2 0 -3 3 -3 4 -2 2 -1 -3 2 1

B =

8 5 7 6 10 9 10 5 11

ans =

10 5 4 3 3 14 7 2 9 2 13 1

ans =

2 0 -3 3 8 5 7 -3 4 -2 2 6 10 9 -1 -3 2 1 10 5 11

(a) (b) (c)

Page 20: Arrays – Part 2

20

II. addition/subtraction (example4)

• Assume the matrices A and B below.

>>C = B-A <enter> results in?

??? Error using ==> minusMatrix dimensions must agree.

(a) (b)

A =

2 3 -2 5 1 2 -2 -2

B =

4 11 5 8 9 10 7 12

ans =

2 8 7 3 8 8 9 14 Neither (a) nor (b)

(c)

Page 21: Arrays – Part 2

21

II. addition/subtraction (Rule #1)

• Addition and subtraction between arrays (vectors OR matrices) can be done if and only if BOTH dimensions match.

(2 x 3) (2 x 3)

– By “dimensions”, understand “number of rows of A and B are equal, and number of columns of A and B are equal”

• This does not mean “Square”

– A 3by4 can be added or subtracted to a 3by4.– A 100by200 can be added or subtracted to a 100by200.– A 5by4 cannot be added to a 4by5.– A 5by5 can be added to a 5by5.

Page 22: Arrays – Part 2

22

Exception to rule #1

• Adding or subtracting a scalar (a 1 by 1 array) to any array is possible. – MATLAB assumes the operation is done on each element per default.

A =

2 4 5 3 3 8 2 2 4 3 6 4 6 6 6

>> A+2 <enter> results in?

Answer:

A is a 3by5

2 is a 1by1

It still works!

ans =

4 6 7 5 5 10 4 4 6 5 8 6 8 8 8

Page 23: Arrays – Part 2

Multiplication/Division/Power

• Linear Algebra has its own way of multiplying matrices. You’ll learn all about it in MA 345.

• MATLAB defaults to matrix multiplication.

Page 24: Arrays – Part 2

24

Matrix Multiplication the Linear Algebra way

• Matrices can be multiplied together if and only if the inner dimensions match

(2 x 3) * (3 x 3) = (2 x 3)

(4 x 3) * (3 x 1) = (4 x 1)

• The resulting dimension is the outer dimensions.

“inner dimensions”

Page 25: Arrays – Part 2

25

Matrix Multiplication the Linear Algebra way

• A is a (2by3) matrix and B is a (3by4) matrix:

True or False >>A*B <enter> is a valid statementTrue or False >>B*A <enter> is a valid statement

>>C = A*BC will be a __ by __ matrix.2 4

>> B*AError using * Inner matrix dimensions must agree.

Page 26: Arrays – Part 2

26

Matrix Division

• To divide a matrix A by a matrix B really means:“To multiply matrix A by the inverse of matrix B” “inverse” does not mean “transpose”.

All the rules of multiplications apply

• The inverse of a matrix is possible if and only if it is “square”: it has the same amount of rows as columns.

>> A/B for example: (2by3) / (3by3) means (2by3) * inv(3by3) means (2by3) * (3by3) will work.

a/b is really a*(1/b)

Page 27: Arrays – Part 2

But I’m not in MA 345 yet…

• The majority of how you’ll use matrices in EGR115 will NOT be using the linear algebra method.

Page 28: Arrays – Part 2

28

Multiplying/Dividing by a Scalar

• Multiplying together a matrix and a scalar (a 1 by 1 array) to any array is possible. – MATLAB assumes the operation is done on each element per default.

• Note: the inner dimension obviously don’t match, so A*A wouldn’t work.

A =

2 4 5 3 3 8 2 2 4 3 6 4 6 6 6

>> A*2 <enter> results in? Answer:

Page 29: Arrays – Part 2

29

Multiplying/Dividing by a Scalar

• Dividing a matrix by a scalar (a 1 by 1 array) is possible. – MATLAB assumes the operation is done on each element bydefault.

• CAUTION: Dividing a scalar by an array is impossible.

Page 30: Arrays – Part 2

30

What if arrays don’t represent MATRICES

• In MATLAB, an array of multiple dimensions represents a MATRIX.– Any operation (+-*/^) on these is dealt with following strict mathematical

rules

• What if an array is simply used as a database of numbers?– use the element by element operators

.* ./ .^

A =

5 5 8 9

A^3 =

5 5 8 9

5 5 8 9

5 5 8 9* *

A^3 IS NOT

5^3 5^3 8^3 9^3=

885 955 1528 1649

Page 31: Arrays – Part 2

31

Example Calculating Prices

Assume the two following vectors:– One is the quantity bought of each item (1-5)

– The second is the price of each item (1-5)

Calculate the total bill ($)

So: quantities.*prices , then add all?

2 3 6 4 3

20.00 10.50 5.50 10.00 25.00

2*20

3*10.5

6*5.5

4*10

3*25

quantities

prices

= $219.50

+ + + +

Page 32: Arrays – Part 2

The Dot Operator

• Any time you need to do math on an element-by-element basis (which will be most of the time in EGR115), you need to use the dot before the multiplication, division, and exponentiation sign.

A =

5 5 8 9

A^3 =

5 5 8 9

5 5 8 9

5 5 8 9

A^3 IS NOT

5^3 5^3 8^3 9^3

885 955 1528 1649* * =

A.^3 IS

5^3 5^3 8^3 9^3

Page 33: Arrays – Part 2

Basic functions on arrays

CAUTION: A function will return different values depending on whether the argument is a vector or a matrix!Built-in function Argument is a vector Argument is a matrixmin() Returns the minimum value of the

vectorExtracts the minimum of EACH column-> returns a vector

max() Returns the maximum value of the vector

Extracts the maximum of EACH column-> returns a vector

mean()

NOT avg()!!!!

AUTOMATICALLY adds all the elements in the vector together and divides by the number of elements!

Extracts the average of EACH column-> returns a vector

Page 34: Arrays – Part 2

Basic functions on arrays

• Rule of thumb:– If your input is a vector, it will apply the function to all the elements in

the array, regardless of if the vector is a row or column vector– If your input is a matrix, it will apply the function to each column and

return a vector corresponding to the results from each column.

Page 35: Arrays – Part 2

Ex. vector: Temperatures

clcclear

% engine temperaturetemps = [45.5,56.7,99.9,42,12,29];

% determine minimum,maximum,average temperatureminTemp = min(temps)maxTemp = max(temps)avgTemp = mean(temps)

Do not use min =, or max=…, or mean= …These keywords are reserved by MATLAB!

Page 36: Arrays – Part 2

36

Ex. matrix: Scoresclcclear

% scores from playing. Col1 = player1, col2 = player2…etc.scores = [45,34,56; 67,3,45; 22,55,99]’; %transposed!

% determine minimum,maximum,average scoresminScores = min(scores) ?maxScores = ______________avgScores = ______________

Page 37: Arrays – Part 2

ARRAY REFERENCING

3737

Page 38: Arrays – Part 2

38

II. Array Referencing

• Assume an array has values. It is useful to “refer to” the elements contained within it – as smaller portions of the array or even individually.

• Because the values contained within the array may change when the program runs, the index (i.e. position) of the elements allows a mean of accessing them.

• MATLAB starts counting at 1.

? …

? …

3RD

Page 39: Arrays – Part 2

39

II. Array Referencing

• How to refer to elements within a scalar? A vector? A matrix?

• A scalar has one single value – simply refer to the variable itself.age

• A vector has one dimension regardless whether it’s a row vector or a column vector. Use a single index to reference the values in a vector:ages(2)

• A matrix has two or more dimensions. Use an index for EACH dimension: FIRST: a row number, SECOND: a column numberpressures(3,56)

(More dimensions? Use another number for each additional dimension!)

Page 40: Arrays – Part 2

Array Referencing - Vectors

• Vectors use a single value. Each value is called an “index”:x = [5; -1; 4]; %original vectorsum = 0; %start sum at zerosum = sum + x(1); %add first elementsum = sum + x(2); %add second

elementsum = sum + x(3); %add third element

40

Index

This process of repeatedly adding numbers to a single variable is called a “running sum”

Page 41: Arrays – Part 2

Array Referencing - Vectors

• Vectors use a single value. Each value is called an “index”:x = [5; -1; 4]; %original vectorsum = 0; %start sum at zerosum = sum + x(1); %add first elementsum = sum + x(2); %add second

elementsum = sum + x(3); %add third element

• Vectors have one dimension, so use a single index in parentheses to specify which element to use. Indexing starts at 1, and can go as high as how-many-elements-there-are.Yes, it seems quite repetitive… wouldn’t a loop make it easier? Hang in there…

41

Page 42: Arrays – Part 2

Array Referencing - Matrices

• Matrices are similar. To access the 6 in this matrix:

M = [1, 2, 3; 4, 5, 6; 7, 8, 9]

Use : M(2,3)

42

Row number always first!

Column number always second!

Page 43: Arrays – Part 2

Array Referencing - Matrices

• Matrices are similar. To access the 6 in this matrix:

M = [1, 2, 3; 4, 5, 6; 7, 8, 9]

Use : M(2,3)

• It can be used directly:

x = 7 * M(2,3); %Result? _____

43

Row number always first!

Column number always second!

42

Page 44: Arrays – Part 2

Array Referencing - Matrices

• Matrices are similar. To access the 6 in this matrix:

M = [1, 2, 3; 4, 5, 6; 7, 8, 9]

Use : M(2,3)

• It can be used directly:

x = 7 * M(2,3); %Result? _____

• The row and column positions specified in the parentheses are referred to as “indices” (plural of “index”): 2 is the “row index” and 3 is the “column index”.

44

Row number always first!

Column number always second!

42

Page 45: Arrays – Part 2

Referencing

• To refer to “all” of a column or row, use the range operator by itself:

V = M(:, 3); %from M, copy all rows in columns 3 to V

4545

The same can be done with columns!

V = M(2, :); % V gets a copy of all columns of row 2

Page 46: Arrays – Part 2

ARRAY SLICINGAccessing more than one element of an array

4646

Page 47: Arrays – Part 2

Array Slicing

In general, a slice is a "smaller piece" of something. The range operator is frequently used when getting a slice.

% Copy all elements in rows 1 and 2,

% columns 1 through 4

47

… …

Page 48: Arrays – Part 2

Array Slicing

In general, a slice is a "smaller piece" of something. The range operator is frequently used when getting a slice.

% Copy all elements in rows 1 and 2,% columns 1 through 4M1 = M(___ ,____);

48

Page 49: Arrays – Part 2

Array Slicing

In general, a slice is a "smaller piece" of something. The range operator is frequently used when getting a slice.

% Copy all elements in rows 1 and 2,% columns 1 through 4M1 = M(1:2 ,____);

49

Page 50: Arrays – Part 2

Array Slicing

In general, a slice is a "smaller piece" of something. The range operator is frequently used when getting a slice.

% Copy all elements in rows 1 and 2,% columns 1 through 4M1 = M(1:2 ,____);

50

Page 51: Arrays – Part 2

Array Slicing

In general, a slice is a "smaller piece" of something. The range operator is frequently used when getting a slice.

% Copy all elements in rows 1 and 2,% columns 1 through 4M1 = M(1:2,1:4);

51

Page 54: Arrays – Part 2

ARRAY DIMINUTION

Making arrays smallerDeleting an element, a row, a column, etc..

5454

Pronounce:“Dim’ – min – yoo’ – shun”

Page 55: Arrays – Part 2

Array Diminution

• To eliminate the whole content, re-define it as an empty-vector:

scores = []; %delete all scores

• To eliminate a single value from a vector, either take a slice:HighScores = [757, 65, -13, -89];HighScores = HighScores(1:3);%deletes last score

Or use the empty-vector:HighScores(4) = []; %removes 4th score

55

Page 56: Arrays – Part 2

Example Diminution

• After analyzing data, get rid of some data: in this case, assign the empty brackets []

• For example, get rid of the number 8 in b below:

56

This action changes the original vector and cannot be undone.

Page 57: Arrays – Part 2

Example Diminution

• After analyzing data, get rid of some data: in this case, assign the empty brackets []

• For example, get rid of the number 8 in b below:

57

This action changes the original vector and cannot be undone.

Page 58: Arrays – Part 2

Array Diminution, cont.

• To eliminate an entire row/column:1. Use the range operator, combined with2. the empty-vector

M = [1, 2, 3; 4, 5, 6];

M(:, 1) = [] … Read it as:

58

%”M

Page 59: Arrays – Part 2

Array Diminution, cont.

• To eliminate an entire row/column:1. Use the range operator, combined with2. the empty-vector

M = [1, 2, 3; 4, 5, 6];

M(:, 1) = [] … Read it as:

59

%”M , all-rows

Page 60: Arrays – Part 2

Array Diminution, cont.

• To eliminate an entire row/column:1. Use the range operator, combined with2. the empty-vector

M = [1, 2, 3; 4, 5, 6];

M(:, 1) = [] … Read it as:

60

%”M , all-rows, 1stcolumn

Page 61: Arrays – Part 2

Array Diminution, cont.

• To eliminate an entire row/column:1. Use the range operator, combined with2. the empty-vector

M = [1, 2, 3; 4, 5, 6];

M(:, 1) = [] … Read it as:

61

%”M , all-rows, 1stcolumn , delete!”

Page 62: Arrays – Part 2

Array Diminution, cont.

Question:

• Can we eliminate a single value from a matrix?

M = [1, 2, 3; 4, 5, 6];M(2, 2) = [] <enter>

62

Page 63: Arrays – Part 2

Array Diminution, cont.

Question:

• Can we eliminate a single value from a matrix?

M = [1, 2, 3; 4, 5, 6];M(2, 2) = [] <enter>

63

No – because that would mean some rows or columns would have more values than others.

Page 64: Arrays – Part 2

AUGMENTING AN ARRAYInsert values at the end of an array (not in the middle, nor beginning)

6464

Page 65: Arrays – Part 2

Array Augmentation, review

Augmentation = “Adding to” = making an array bigger. For example:V = [1, 2, 3];

To augment more columns, it’s much like doing a running total or running product: to the current variable, perform an action:

V = [V, 4, 5, 6];

65

Result: [ ___________________ ] ?

65

1, 2, 3 , 4, 5, 6

Page 66: Arrays – Part 2

Array Augmentation, review

Augmentation = “Adding to” = making an array bigger. For example:V = [1, 2, 3];

To augment more columns, it’s much like doing a running total or running product: to the current variable, perform an action:

V = [V, 4, 5, 6];

To augment with another row vector variable:V1 = [3, 4, 5];V2 = [6, 7, 8];V1 = [V1; V2];

66

Makes a matrix!

Result:__ __ __.

__ __ __.

66

1, 2, 3 , 4, 5, 6Result: [ ___________________ ] ?

3, 4, 5

6, 7, 8

Page 67: Arrays – Part 2

Array Augmentation, review

Augmentation = “Adding to” = making an array bigger. For example:V = [1, 2, 3];

To augment more columns, it’s much like doing a running total or running product: to the current variable, perform an action:

V = [V, 4, 5, 6];

To augment with another row vector variable:V1 = [3, 4, 5];V2 = [6, 7, 8];V1 = [V1; V2];

To augment with a column vector variable:V1 = [6; 8; 9];V2 = [10; 20; 30];V1 = [V1, V2];

67

Makes a matrix!

Why use a comma? ________________

Result:__ __ __.

__ __ __.

Result:__ __ .

__ __ __ __

67

Result: [ ___________________ ] ?1, 2, 3 , 4, 5, 6

3, 4, 5

6, 7, 8

68

9

1020

30

Page 68: Arrays – Part 2

Array Augmentation, review

• Works for matrices, too:

M1 = [1, 2, 3; 4, 5, 6]; %original matrixM1 = [M1; 7, 8, 9]; % attach a row to M1M1 = [M1, [11, 2, 33; 44, 33, 22; 1, 0, 2]]

M1 =

1 2 3 11 2 33 4 5 6 44 33 22 7 8 9 1 0 2

68

Be sure to augment with the correct number of rows / columns!

68

Page 69: Arrays – Part 2

Extending an array

69

Matrix b does not have 4 columns… mmm… what will it do?

Page 70: Arrays – Part 2

Extending an array

70

Fills in with zeros.

Page 71: Arrays – Part 2

71

Key Ideas

I. Hardcoding arrays [] , ; : ‘Prefer these symbols when arrays are small, NOT when arrays are big.

Exception: the colon can technically create big arrays instantly.II. Referencing

• Index = position number• Use one index in vectors vector(index number)• Use two indices in matrices matrix(row, colum)

III. Common operations• Slicing: concentrating on a piece of an array• Diminution: getting rid of elements. Use =[ ]; • Augmenting: “adding values” – increasing the size of an existing array• Combine any symbols/method, as long as the array created is rectangular!

IV. Common functions• sum() prod() mean() max() min()• Different results when applied to vector compared to matrices

Go ahead, use MATLAB and arrays to check your math homework!

Page 72: Arrays – Part 2

72

Helpful functions

• How many elements are in the array?

Function Return value

length(vector) Number of elements in the vector

length(matrix) Highest dimension

size(matrix,1) Number of rows in the matrix

size(matrix,2) Number of columns in the matrix

size(matrix) 1 by 2 array of row and column dimensions

numel(array) Number of elements total in the array