720 likes | 897 Views
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:
E N D
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.
2.2. Patterns (addition only) • For addition pattern, no need to code a lot! The range operator Numbers are separated by +1
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
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
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.
>>doc linspace<enter> linspace Generate linearly spaced vectors Syntax y = linspace(a,b)y = linspace(a,b,n) Description The 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 rowvector 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.
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.
2.3. linspace(), cont. • Transpose the return value of linspace() to create a column vector
2.3. linspace(), cont. ?????? %no third argument Omitthe third argument uses a default of _______ data points!
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
3.1. Matrices: hard-coding • Use semi-colons to create new rows. • Good or bad? Why? 2 by 3 3 by 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
3.3 Using colons • Combine ALL methods necessary JUST KEEP THE ARRAY RECTANGULAR
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 Wikipedia This is an “n-by-p” matrix. n rows, p columns.
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)
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)
II. addition/subtraction (example3) • 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 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)
II. addition/subtraction (example4) • Assume the matrices A and B below. >>C = B-A <enter> results in? 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 ??? Error using ==> minus Matrix dimensions must agree. Neither (a) nor (b) (c) (a) (b)
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.
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? ans = 4 6 7 5 5 10 4 4 6 5 8 6 8 8 8 Answer: 2 is a 1by1 A is a 3by5 It still works!
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.
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”
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 statement True or False >>B*A <enter> is a valid statement >>C = A*B C will be a __ by __ matrix. 4 2 >> B*A Error using * Inner matrix dimensions must agree.
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)
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.
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:
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.
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 A^3IS NOT 5^3 5^3 8^3 9^3 5 5 8 9 5 5 8 9 885 955 1528 1649 * * =
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? quantities prices + + + + = $219.50
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^3IS NOT 5^3 5^3 8^3 9^3 A = 5 5 8 9 A^3 = 5 5 8 9 A.^3IS 5^3 5^3 8^3 9^3 5 5 8 9 5 5 8 9 885 955 1528 1649 = * *
Basic functions on arrays CAUTION: A function will return different values depending on whether the argument is a vector or a matrix!
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.
Ex. vector: Temperatures clc clear % engine temperature temps = [45.5,56.7,99.9,42,12,29]; % determine minimum,maximum,average temperature minTemp = min(temps) maxTemp = max(temps) avgTemp = mean(temps) Do not use min =, or max=…, or mean= … These keywords are reserved by MATLAB!
Ex. matrix: Scores clc clear % scores from playing. Col1 = player1, col2 = player2…etc. scores = [45,34,56; 67,3,45; 22,55,99]’; %transposed! % determine minimum,maximum,averagescores minScores= min(scores) ? maxScores= ______________ avgScores= ______________
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
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 number pressures(3,56) (More dimensions? Use another number for each additional dimension!)
Array Referencing - Vectors • Vectorsuse a single value. Each value is called an “index”: x = [5; -1; 4]; %original vector sum = 0; %start sum at zero sum = sum + x(1); %add first element sum = sum + x(2); %add second element sum = sum + x(3); %add third element Index This process of repeatedly adding numbers to a single variable is called a “running sum”
Array Referencing - Vectors • Vectors use a single value. Each value is called an “index”: x = [5; -1; 4]; %original vector sum = 0; %start sum at zero sum = sum + x(1); %add first element sum = sum + x(2); %add second element sum = 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…
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) Row number alwaysfirst! Column number always second!
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? _____ Row number alwaysfirst! Column number always second! 42
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”. Row number alwaysfirst! Column number always second! 42
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 The same can be done with columns! V = M(2, :); % V gets a copy of all columns of row 2 45
Accessingmore than one element of an array ARRAY SLICING 46
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
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 M1 = M(___ ,____);
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 M1 = M(1: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, % columns1 through 4 M1 = M(1:2 ,____);