Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.

Similar presentations


Presentation on theme: "Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect."— Presentation transcript:

1 Arrays 1 Multiple values per variable

2 Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect data from the user and be able to work with the individual pieces afterwards. I don’t know how much data there will be. How do I store this incoming information?

3 1. Creating scalars Assign a value to a variable (i.e. Hardcode) pressure = 10; % Pascals temperature = 298; % kelvin

4 2.1. row vector Square brackets [] and commas OR square brackets and white space 1 by 4

5 2.1. column vector Square brackets and semi-colons Or a row vector transposed with the apostrophe 3 by 1

6 New operators… [] Use [] to tell MATLAB you are about to hardcode an array, Use a comma or white-space to create new columns ; Use semi-colons to create a new row ’ Use an apostrophe to transpose the array (caution if you are using imaginary numbers) NO MATTER WHAT YOU DO: ALWAYS KEEP THE ARRAY RECTANGULAR!!!!!

7 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 X

8 3.1. Matrices: hard-coding Use semi-colons to create new rows. Good or bad? Why? 2 by 33 by 2

9 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 a 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.

10 2.2. Patterns For patterns, there’s no great need of code! The range operator Numbers are separated by +1

11 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 

12 2.2. Patterns, cont. Create a decreasing pattern by using a negative increment! CAUTION: Now the beginning number must be > the end number. Note: it works with fractional values. -2.5 -2.5 -2.5 < 3 

13 2.3. Specific number 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.

14 >>doc linspace 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 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.

15 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.

16 2.3. linspace(), cont. Transpose the return value of linspace() to create a column vector

17 2.3. linspace(), cont. ?????? %no third argument Omit the third argument uses a default of _______ data points!

18 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 X

19 3.1. Matrices: hard-coding Use semi-colons to create new rows. Good or bad? Why? 2 by 33 by 2

20 3.2. Concatenating matrices Assume variable a from the previous slide. Use it as a reference to create a new variable: “CONCATENATING” The act of “gluing” vectors and matrices together

21 3.3 Using colons Combine ALL methods necessary JUST KEEP THE ARRAY RECTANGULAR

22 Array Building Array Building is the technique analogous to running totals – take an existing array and “augment it”, storing it back into the same variable: my_array = []; value = input('An integer: '); my_array = [my_array, value];

23 Terminology Concatenation To “glue together” two or more items to make a single item Augmentation To make an item bigger by appending / prepending / insertion Diminution To make an item smaller by removal

24 WHAT TO DO WITH THEM??? Creating arrays is great but…

25 Actual uses of Arrays

26 What if I need lots of data? We’ll talk in more detail about reading from and writing to files later, but we want to give you a basic tool to work with for now. Data must be neatly organized Data must be separated by a single consistent character – Comma, space, and tab are the most common, but it can be anything – It must be the same thing throughout. You can’t mix & match. Data cannot contain anything except numbers Each row must be formatted the same way Your data file(s) must be in the same directory as your script

27 dlmread() Syntax M = dlmread(filename); Reads numeric data from the ASCII delimited file filename, and returns the data in output matrix M. The input filename is a string enclosed in single quotes. The delimiter is inferred from the formatting of the file. M = dlmread(filename, delimiter); Reads numeric data from the ASCII delimited file filename using the delimiter delimiter such as '-', ':' and etc. (Use '\t' to specify a tab.) >>doc dlmread open further possible syntaxes 27

28 Delimiter inferred Delimiter: white space (spaces, or tabs) 28 Missing data is filled by zeros. Use ' ' for the filename

29 3.3 Delimiters inferred, cont. Delimiter: commas Added feasibility to ‘skip’ columns 29

30 3.3 Specific Delimiters, cont. Delimiter: other than the defaults 30 Specify the delimiter as the 2 nd argument.

31 Testing habits Though the file may contain 1,000,000 lines, and ONE command does the job, it is best to test the analysis with a smaller file: – create a copy of the original file, where only 5-10 lines are present. 31

32 Array Math

33 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 33 Wikipedia This is an “n-by-p” matrix. n rows, p columns.

34 II. addition/subtraction (example1) Assume the vectors (actual math vectors) shown here >>v1+v2+v3 results in? 34 v1 = 2 -3 v2 = 4 -2 v3 = 4 ans = 2 4 -1 -3 -2 4 ans = 5 (a)(b)

35 II. addition/subtraction (example2) Assume the matrices A and B below. >>A+B results in? 35 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)

36 II. addition/subtraction (example3) Assume the matrices A and B below. >>A+B 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)

37 II. addition/subtraction (example4) Assume the matrices A and B below. >>C = B-A results in? 37 ??? Error using ==> minus Matrix 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)

38 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. 38

39 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 by default. 39 A = 2 4 5 3 3 8 2 2 4 3 6 4 6 6 6 >> A+2 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

40 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.

41 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. Matrix Multiplication the Linear Algebra way 41 “inner dimensions”

42 Matrix Multiplication the Linear Algebra way A is a (2by3) matrix and B is a (3by4) matrix: True or False >>A*B is a valid statement True or False >>B*A is a valid statement >>C = A*B C will be a __ by __ matrix. 42 24

43 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”, nor “reciprocal”  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. 43 a/b is really a*(1/b)

44 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.

45 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. 45 A = 2 4 5 3 3 8 2 2 4 3 6 4 6 6 6 >> A*2 results in? Answer:

46 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. 46

47 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.*./.^ 47 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

48 Example 48 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? 23643 20.0010.505.5010.0025.00 2* 20 3* 10.5 6* 5.5 4* 10 3* 25 quantities prices = $219.50 ++++

49 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


Download ppt "Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect."

Similar presentations


Ads by Google