Download presentation
Presentation is loading. Please wait.
Published byDiane Perry Modified over 9 years ago
1
1 Chapter 3 Arrays (2) 1. Array Referencing 2. Common Operations 1. Slicing 2. Diminution 3. Augmentation 3. List of Commonly Used Built-in Functions 1. Applied to vectors 2. Applied to matrices 4. Traversing an Array 1
2
ARRAY REFERENCING Accessing the elements within the array 22
3
Array Referencing Once you have an array, we sometimes need to refer to the elements contained within it – as smaller portions of the array or even individually. Because our programs cannot know the values contained within the variable when we write it, we must refer to the positions of the elements as a more general means of accessing them. 3 ?… ?… 3 RD
4
Array Referencing, cont. We refer to the positions using “dimensions” – based upon how many dimensions make up a variable: A scalar has no dimensions – we simply refer to the variable itself. A vector has one dimension – either a number of rows or a number of columns. We use a single number to reference the values in a vector. A matrix has two or more dimensions. We use a number for EACH dimension: a row number, AND a column number (Typically - matrices with more dimensions would use another number for each additional dimension)
5
Array Referencing - Scalars x = 7; y = x + 5; We referenced the scalar x as the variable itself. 5
6
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 we use a single index in parentheses to specify which element we are using. Indexing starts at 1, and can go as high as how-many-elements-there-are. Yes, it seems quite repetitive… couldn’t we use a loop or something to make it easier? Hang in there… 6
7
Array Referencing - Matrices Matrices are similar. To access the 6 in this matrix: M = [1, 2, 3; 4, 5, 6; 7, 8, 9] we would say: M(2,3) It can directly be used in equations: x = 7 * M(2,3); %Result? _____ The row and column positions specified in the parentheses are referred to as “indices” (plural of “index”). We say that 2 is the “row index” and 3 is the “column index”. Row number always first! Column number always second! 7
8
Array Referencing, cont. But, we don’t have to use constants for the indices. We can also use variables: Instead of saying M(2,3), we can say: r=2; c=3; x = y + M(r, c); 8
9
Referencing - (Nested FOR Loops) “So what?”, you say. Well, with the power of loops it should become obvious. We can add up all of the values in a matrix, but only if we refer to each one: sum = 0; for r = 1:3 for c = 1:3 sum = sum + M(r, c); end The row index is gotten from a variable! The column index is gotten from a variable! 9
10
Referencing – Nested loops sum = 0; for r = 1:3 for c = 1:3 sum = sum + M(r, c); end Notice that the inner loop is changing its value while the outer loop waits. Only when the inner loop is complete does the outer loop increment. Why did we choose “r” and “c” for the loop variables? In this version, we move across all columns in a row before we proceed to the next row. Did we have to do this? If we choose to move down through all rows of a column before moving onto the next column, how would these loops change?
11
Referencing – (The range operator…) If you want to refer to “all” of a column or row, you can use the range operator by itself: V = M(:, 3); % from M, copy all rows in columns 3 to V 11 Note: The same could be done with columns! V = M(2, :); % Copy all columns of row 2 to V
12
ARRAY SLICING Used for: Accessing more than one element of an array Eliminating bad elements 12
13
Array Slicing In general, when we “pull out” part of an array, we call that a “slice”. The range operator is frequently used when getting a slice. % Pull out all elements in rows 1 and 2 % that are in columns 1 through 4 M1 = M(1:2, 1:4); 13
14
Real-life #1: Eliminating bad data In wind tunnels, the data is obtained throughout the tunnel. However, data is usually flawed around the walls, or far away form the object itself. Given an array of pressure/temperature/or density obtained, only the ones far from the wall are kept for analysis! 14
15
ARRAY DIMINUTION Making arrays smaller Deleting an element Deleting a row Deleting a column 15 Pronounce: “Dim’ – min – yoo’ – shun”
16
Array Diminution To eliminate the whole content, just re-define it as an empty-vector: scores = []; %delete all scores To eliminate a single value from a vector, you can either take a slice: HighScores = [757, 65, -13, -89]; HighScores = HighScores(1:3); %deletes last %score Or you can use the empty-vector: HighScores(4) = []; %removes 4 th score 16
17
Example Diminution After analyzing data, you may wish to get rid of some data: in this case, assign the empty brackets [] For example, get rid of the number 8 in b below: 17 This action changes the original vector and cannot be undone.
18
Array Diminution, cont. To eliminate an entire row/column: 1. Use the range operator, combined with 2. the empty-vector M = [1, 2, 3; 4, 5, 6]; M(:, 1) = [] … Read it as: QUESTION: Can we eliminate a single value from a matrix? M(2,2) = [] ? No – because that would mean some rows or columns would have more values than others. 18 %”M, all-rows, 1 st column, delete!”
19
Real life#2 – similar example 19 Clearly, bad results on the walls…
20
20 Real life#2 – similar example
21
21 Real life#2 – similar example
22
22 Real life#2 – similar example Suppose you want to delete the top now, since that is also a wall in the wind tunnel. What would be the command line? ____________________________________
23
AUGMENTING AN ARRAY 23
24
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]; Makes a matrix! Why did we use a comma? ________________ Result: _ [ _________________ ] _? Result: __ __ __. Result: __ __. __ 24
25
Array Augmentation, review Works for matrices, too: M1 = [1, 2, 3; 4, 5, 6]; %original matrix M1 = [M1; 7, 8, 9]; %add a row to M1 M1 = [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 Be sure that you augment with the correct number of rows / columns! 25
26
Extending an array 26 Array b does not have 4 columns… mmm… what will it do?
27
27 Commonly Used Built-In Functions 27
28
Common Array Functions 28 1. To create arrays2. To analyze arrays2. To loop through arrays zeros()max()length() ones()min()numel() rand()mean()size() sum() prod() sort()
29
1. TO CREATE ARRAYS No hardcoding Arrays useful and easy to create 29
30
Creating Special Arrays zeros() to create arrays with zeros e = zeros(nb of rows, nb of columns) ones() to create arrays with ones f = ones(nbRows, nbCols) rand() to create arrays with numbers between 0 and 1. g = rand(nbRows, nbCols) 30
31
Creating Special Arrays, cont. zeros() to create arrays with zeros e = zeros(one argument only) ones() to create arrays with ones f = ones(one argument only) rand() to create arrays with numbers between 0 and 1. g = rand(one argument only) 31 >> zeros(3) ans = 0 0 0 >> ones(3) ans = 1 1 1 >> rand(3) ans = 0.8147 0.9134 0.2785 0.9058 0.6324 0.5469 0.1270 0.0975 0.9575
32
2. VECTOR ANALYSIS max(), min(), mean(), sum(), prod(), sort() 32
33
33 Example of using max() 2 different ways Note: max_of_b and where are arbitrary names. You could (but not should) pick blabla1 and blabla2 instead… HOWEVER: you must have two variables in THAT order: 1 st will represent the value, 2 nd will represent the position of the maximum This is the first time we’ve seen a function return multiple values. As you can see, the only change we made was that we decided that we wanted to save the second value instead of ignoring it Only collected a single return value Collecting two return values – but same function call!
34
3. MATRIX ANALYSIS max(),min(),mean(),sum(),prod(),sort() - huh? Again? Yes! 34
35
Library functions sum(), prod(), mean(), max(), min() have a different result than when applied to vectors vs. matrices By default, the operations are done on each column, thus giving the sum/product/average/max or min of each column. You can choose to apply the operation to any dimension, but you have to use the two-argument version: sum(x, 2) 1 = sum the elements in all rows (i.e. down the column) 2 = sum the elements in all columns (i.e. across the row) 3 = sum the elements in each row and column (i.e across “pages”) – 3Dimensional The result of these functions on an array is a vector. If you want the sum of a whole array, use sum(sum(arrayName)) 35
36
Using the sum() 36 The same rules apply for mean(), prod() NOT for min(), max(),
37
Sorting arrays There are two fundamental tasks when working with computer data: sorting and searching. You can build a PhD thesis out of efficiency of sorting and searching! Fortunately, we don’t have to – we’ll just use some MATLAB functions 37
38
Sorting Arrays, cont. Like sum(), max(), min(), etc., the sort() function works along the columns by default. But you can change that: >> a a = 1 2 3 4 5 6 >> sort(a, 2, 'descend') ans = 3 2 1 6 5 4 2 = sort all the columns in a row 2 This is the first time we’ve seen a non-numeric argument. Like numeric arguments, which non- numeric values are valid is determined by the function. Refer to the Help (F1 in MATLAB) for more info about each function. The sort() function has two possible values for the 3 rd argument: ‘ascend’ and ‘descend’. By default (if you don’t specify a third argument) the function sorts in ascending order.
39
Dimension of an array size() is a built-in function that returns a new vector with 2 values inside: the number of rows (first), the number of columns (second) length() is another built in function that returns the maximum value between the number of rows and columns of an array 39
40
TRAVERSING AN ARRAY My friend, the FOR loop Analyze an array in other ways than max,min,sort… 40
41
Linear Searching “Linear searching” is exactly how we typically work a search – we look at each element and see if it matches. We stop when we reach the end of the array. For example: Our program has generated a matrix. We would like to know if any value in the matrix exceeds the value of 10.
42
Linear Searching, cont. s = size(M); found = []; for r = 1:s(1) for c = 1:s(2) if M(r, c) > 10 found(1) = r; found(2) = c; end size() gives us # of rows and # of columns found will contain the position of the last value found that is greater than 10
43
Binary Searching Binary searching is a fancy name for how we use the phone book – an extremely fast way to search. Since names are sorted in the phone book, we can skip massive portions. For example, if the last name starts with “T”, we can skip about 75% of the phonebook!
44
Binary Searching, cont. Just like with the phonebook, we can search arrays using binary searching. And like the phonebook, this method requires that the information already is sorted. Although it can be modified for matrices, it is most useful when searching vectors.
45
Binary Searching, cont. To use binary searching: Sort the vector Repeat until found or run out of values to check Compute the ½ way index for the current range Is it what you want? If not, is it too high or too low? If too high, move to middle of lower range If too low, move to middle of upper range
46
Binary Searching, cont. clear clc % Give us some values v = floor(25*rand(1, 10)) % Search for the value 10 value = 10; % Sort the data v = sort(v) % Setup the vars hi = 10; lo = 1; done = false; found = false; while (~done && ~found) range = hi - lo + 1; index = floor(range / 2) + lo; if (v(index) == value) found = true; elseif (v(index) > value) hi = index-1; else lo = index+1; end if hi<lo done = true; end Repeat until found or run out of values to check Compute the ½ way index for the current range Is it what you want? If too high, move to middle of lower range If too low, move to middle of upper range Have we used up all the values?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.