21
1 Arrays in Matlab Why arrays? Calculate statistics for 100 high temperatures from the last 100 days. temp1 = 82 temp2 = 78 ... temp100 = 81 Tedious and error-prone Need a way to concisely represent related data Array Collection of related numbers Arranged in rows and/or columns Stored in a single variable A variable holding a single value, such as we have seen up until now, is called a scalar. value = 5 % value is a scalar

Arrays in Matlab

  • Upload
    vat007

  • View
    253

  • Download
    1

Embed Size (px)

DESCRIPTION

matlab

Citation preview

Page 1: Arrays in Matlab

1

Arrays in Matlab

Why arrays?

• Calculate statistics for 100 high temperatures from the last 100 days.

temp1 = 82temp2 = 78...temp100 = 81

• Tedious and error-prone• Need a way to concisely represent related data

Array

• Collection of related numbers• Arranged in rows and/or columns• Stored in a single variable

• A variable holding a single value, such as we have seen up until now, is called a scalar. value = 5 % value is a scalar

Page 2: Arrays in Matlab

2

Row Array

• One variable that consists of n elements• Sometimes called a row vector

Example

• create a row array called temps that holds high temperature readings for four days

temps = [82 78 91 87] ORtemps = [82, 78, 91, 87] (commas are optional)

Creating row arrays

• If the elements have a constant spacing, can use a format similar to the for command

• variable_name = [first : spacing : last] ORvariable_name = first : spacing : last(brackets are optional)

• If spacing is omitted, it is assumed to be 1variable_name = first : last

Page 3: Arrays in Matlab

3

Examples

• W = [1 : 1 : 5]W is 1 2 3 4 5

• X = 1.5 : 0.1: 2.1X is 1.5 1.6 1.7 1.8 1.9 2.0 2.1

• Y = [10 : -2 : 0]Y is 10 8 6 4 2 0

• Z = -3 : 3Z is -3 -2 -1 0 +1 +2 +3

Creating Row Arrays

• If the elements have constant spacing, can also specify the first element, the last element, and the number of elements

• variable_name = linspace (first, last, num)• sample1 = linspace (1, 10, 10)

creates 1 2 3 4 5 6 7 8 9 10• sample2 = linspace (4.2, 10.2, 7)

creates 4.2 5.2 6.2 7.2 8.2 9.2 10.2

Arrays are very powerful

Ex: Draw a sine wave. Array y will automatically have as many elements as array x. plot( ) creates a graph.

x = linspace(0, 2*pi, 100);y = sin(x); plot(x , y)

Page 4: Arrays in Matlab

4

Column Arrays

• Just like a row array, it is one variable that consists of n elements

• Sometimes called a column vector

Creating Column Arrays

A = [10.0; 20.1; 30.6; 120.2] OR

A = [10.020.130.6120.2]

Page 5: Arrays in Matlab

5

Creating Column Arrays

• Can also create column arrays using the other techniques discussed for row arrays.

• Two-step process:– Create a row array– Transpose the array

• Transpose: switch rows to columns or vice versa

• Transpose operator is '

Example

• X = 1 : 1 : 3• Y = X'

X is 1 2 3

Y is 123

Another Example

X = linspace (1, 5, 3)Y = X'

X is 1 3 5

Y is135

Page 6: Arrays in Matlab

6

Yet Another Example

• Array creation and transposition can be combined in one statement

Arr = (1.0 : 0.2 : 1.4)' Arr is1.01.21.4

Subscripts

• Individual array elements accessed by using subscripts

• Subscript is the element number• Subscript must be an integer within the

range of the array

Examples

x = temps (1) % x is 82y = temps(3) % y is 91x = temps (78) %error - subscript too bigtemps(4) = 23 %changes content of last

%element from 87 to 23

Page 7: Arrays in Matlab

7

More Examples

A = [2; 3; 4] % A is 23 4

m = A(1) % m is 2n = A(3) % n is 4A(2) = 7 % A now 2

74

A = [2; 3; 4] %A is 234

for k = 1:1:3 %A is 0A(k) = 0 0

end 0

Still More Examples

• Can use a colon to represent a range of subscripts

• A = [2 4 6 8 10]• B = A(2:4) % B is 4 6 8• A(3:5) = 0 % A is now 2 4 0 0 0

Array Operations

• Two kinds of operations:– Element-by-element, where operations are

performed on each element (next)– Using the rules of linear algebra (later)

Page 8: Arrays in Matlab

8

Assignment Statements

• Contents of one array copied element by element into another array

• Both arrays must be the same size• If new array does not exist, it will be

created to be the same size as the old array

Ex: X = 1: 4 % X is 1 2 3 4Y = X % Y is 1 2 3 4

Scalar - Array Operations

• Apply operation to each element of the arrayX = [1, 2, 3]Y = X + 2 % Y is 3 4 5Y = X - 1 % Y is 0 1 2num = 3Y = X * (num + 1) % Y is 4 8 12Y = X / 2 % Y is 0.5 1 1.5

Example

Plot the equation y = mx + b x should vary between -10 and +10m and b should be chosen by the user

Page 9: Arrays in Matlab

9

Algorithm

• Prompt for and read in m (the slope) and b (the offset)

• Create an array X containing values between -10 and +10

• Create array Y using this formula:Y = m*X + b

• plot X vs Y

Example

m = input ('Please enter the slope: ');b = input ('Please enter the offset: ');X = [-10 : 10];Y = (m * X) + b;plot (X, Y)

-10 -8 -6 -4 -2 0 2 4 6 8 10-8

-6

-4

-2

0

2

4

6

8

10

12

Page 10: Arrays in Matlab

10

Element-by-Element Operations

A = B op C means A(1) = B(1) op C(1) A(2) = B(2) op C(2)

...A(n) = B(n) op C(n)

Where op is + (addition) - (subtraction).* (multiplication)./ (division)

Examples

A = [ 1 2 3]B = [ 4 5 6]C = A + B % C is 5 7 9C = B - A % C is 3 3 3C = A .* B % C is 4 10 18C = B ./ A % C is 4 2.5 2

Two-Dimensional Arrays

• A two dimensional array has rows and columns, like a table

• Sometimes called a matrix

Page 11: Arrays in Matlab

11

Creating Matrices

• Similar to creating vectors (one-dimensional arrays)

• Use commas or spaces to separate elements in a specific row

• Use semicolon or enter to separate individual rows

Examples

A = [1, 2, 3; 4, 5, 6] A is 1 2 34 5 6

B = [1 2 B is 1 23 4 3 45 6] 5 6

Page 12: Arrays in Matlab

12

Creating Matrices

• Can also usefirst: spacing: lastfirst: last (spacing assumed to be 1)linspace (first, last, number)

More Examples

C = [1:2:7; linspace(1,10,4)]C is 1 3 5 7

1 4 7 10D = [0, 0, 3:5 D is 0 0 3 4 5

0, 0, 4:6 0 0 4 5 60 0 7:9] 0 0 7 8 9

Subscripts

• Individual array elements accessed by using subscripts

• Subscript is row number, column number• Both parts of the subscript must be

integers within the range of the array

Page 13: Arrays in Matlab

13

Examples

A = [1 1 1; 2 2 2; 3 3 3] A is 1 1 1

2 2 23 3 3

m = A(1,1) % m is 1n = A(3, 1) % n is 3

Examples, con't

A(2, 2) = 5 A is 1 1 12 5 23 3 3

A(1, 1:3) = 8 A is 8 8 82 5 23 3 3

Examples (con't)

A(1:3, 2) = 7 A is 8 7 82 7 23 7 3

B = [10 10 10]A (1, :) = B A is 10 10 10

2 7 23 7 3

Colon, in this case means all columns. Can also be used for all rows

Page 14: Arrays in Matlab

14

Element by element operations

• Can also be used for 2-dimensional arrays• A = B op C means

A(1, 1) = B(1, 1) op C(1, 1) A(1, 2) = B(1, 2) op C(1, 2)

...A(n, m) = B(n, m) op C(n,m)

• Arrays usually must be same size

Example

ex1 = [1 2 3; 4 5 6]ex2 = [1 1 1; 2 2 2]ex3 = ex1 + ex2ex3 is 2 3 4

6 7 8ex4 = ex1 .* ex2ex4 is 1 2 3

8 10 12

Matrix Multiplication

• Recall that element -by-element multiplication is done using the .* operator

• Can also do matrix multiplication using the rules of linear algebra - uses the * operator

• If C = A*B:– Number of columns in A must equal number

of rows in B– C will have same number of rows as A and

same number of columns as B

Page 15: Arrays in Matlab

15

A Row Times A Column

A = [ A1 A2] B = B1

B2

C = A1*B1 + A2 * B2

Ex: A = [3 - 2] B = 45

C = 3 * 4 + (-2)*5 = 10

Matrix Multiplication

A = A11 A12 B = B11 B12

A21 A22 B21 B22

C11 = A11*B11 + A12 * B21 (row1 * col1)C12 = A11*B12 + A12 * B22 (row1 * col2)C21 = A21*B11 + A22 * B21 (row2 * col1)C22 = A21*B12 + A22 * B22 (row2 * col2)

Matrix Multiplication Example

A = 1 2 B = 5 63 4 7 8

C = (1*5)+(2*7) (1*6)+(2*8)(3*5)+(4*7) (3*6)+(4*8)

C = 19 2243 50

Page 16: Arrays in Matlab

16

General Formula for C = A*B

C(1,1) = (row 1 of A) * (col 1 of B)C(1, 2) = (row 1 of A) * (col 2 of B)...C(2, 1)= (row 2 of A) * (col 1 of B)C(2, 2) = (row 2 of A) * (col 2 of B)...To obtain the i,j entry of C, multiply row i of

A by column j of B

Matrix Multiplication in Matlab

A = [1 4 2; 5 7 3; 9 1 6; 4 2 8];B = [6 1; 2 5; 7 3];C = A * BC = (note that C has same

28 27 number of rows as A 65 49 and same number of 98 32 columns as B)84 38

Matrix Multiplication in Matlab

A = [1 4 2; 5 7 3; 9 1 6; 4 2 8];B = [6 1; 2 5; 7 3];D = B * AError: number of columns in first matrix

must equal the number of rows in second matrix. In this case, 2 ~= 4

Note that matrix multiplication is not commutative: A*B ~= B*A

Page 17: Arrays in Matlab

17

Matrix Division

• Identity matrix is all 0's with 1's on the diagonal. Ex: 1 0 0

0 1 0 0 0 1

• Matrix B is the inverse of matrix A if A*B is the identity matrix.

• Inverse of A is represented as A-1

Matrix Division in Matlab

• Left Division X = A\B equivalent to X = A-1B

• Right Division X = A/B equivalent to X = A B-1

Example: Solving systems of linear

equations

Solve the following systems of linear equations:

4x - 2y + 6z = 82x + 8y + 2z = 46x + 10y + 3z = 0

Page 18: Arrays in Matlab

18

Background

Systems of linear equations can be written as matrices

4 -2 6 x 82 8 2 * y = 46 10 3 z 0

This is of the form AX = BSolving for X: X = A-1B

Algorithm

Create array A from coefficients on left-hand side of equations

Create array B from right-hand side of equations

Solutions = A\B

Matlab Code

A = [4 -2 6; 2 8 2; 6 10 3];B = [8; 4; 0];X = A\B

X = -1.80490.29272.6341

Page 19: Arrays in Matlab

19

Matrix functions

Many, many built-in Matlab functions for use with vectors and matrices

ones(row, col) - create an array of all oneszeros(row, col) - create an array of all zerosA = ones (1, 3) A = 1 1 1B = zeros (2, 3) B = 0 0 0

0 0 0

Matrix Functions

mean: finds the mean of a vectormax: finds the max of a vectormin: finds the min of a vector

A = [1 2 3 4 5];meanA = mean(A) meanA is 3maxA = max(A) maxA is 5

Example

Recall that a row or a column in a matrix is also a vector, so mean max and min can be applied to them also

B = [20 30 40; 50 60 70]max_col1 = max(B(:,1))min_row2 = min(B(2, 1:3))

Page 20: Arrays in Matlab

20

More Matrix Functions

• length - number of elements in a vector• size -size of an array (rows and columns)

B = [1 2 3; 4 5 6]lengthB1 = length(B(1, :)) lengthB1 is 3sizeB = size(B) sizeB is 2 3

Example- Statistics on an array

Assume you are a quality assurance engineer working in a widget factory.

Every hour, you pull 5 widgets off the production line and weigh them.

Calculate the mean weight, the max weight and the min weight. Also, determine if each weight is within its tolerance of 10 lbs plus or minus 0.1 lb.

Algorithm

Put the widget weights into a vectorCalculate and display mean max and minFor each widget weight

if min >= weight >= max display OK

elsedisplay out of tolerance

Page 21: Arrays in Matlab

21

Matlab Code

%initialize array with widget weightsWeight = [9.92 10.05 10.08 9.89 10.12];

%calculate and display mean, max and min

weight_mean = mean(Weight );weight_max = max(Weight );

weight_min = min(Weight );fprintf ('The mean is %.2f, the max is %.2f and the min is

%.2f \n', weight_mean, weight_max, weight_min)

Matlab Code (con't)

%loop through array testing tolerancesfor j = 1 : 1 : 5

if (Weight(j) >= 9.9) & (Weight(j) <= 10.1)fprintf ('Widget %i in tolerance', j)

elsefprintf('Widget %i out of tolerance', j)

endend