230 likes | 687 Views
Traversing an array. Definition Use the for loop Some new functions Use the while loop. Definition. Traversing (verb): Travel across or through: "he traversed the forest". (Google) With respect to arrays (vectors AND matrices), it means look at each element of the array
E N D
Traversing an array Definition Use the for loop Some new functions Use the while loop
Definition • Traversing (verb): Travel across or through: "he traversed the forest". (Google) • With respect to arrays (vectors AND matrices), it means look at each element of the array • Why would traversing an array be useful? • To find the minimum, maximum • To add up all the elements together • To add up only certain elements • To multiply all the elements together • To filter some elements out • To copy elements that match a criteria • To count how many elements fit a criteria • To delete elements that match a criteria
Most practical loop • The loop used to traverse an array: for • Applied to a vector for k = 1:__ %code end • Applied to a matrix for r = 1:__ for c = 1:__ %code end end Number of elements Number of rows Number of columns • NEVER hardcode these values. Keep the code flexible, ready to work for any size of arrays.
Helpful functions • How many elements are in the array?
Example Count the number of elements (vector) Assume this array of dices (values 1 through 6 only) Task: Count how many times each number came out number count • Brainstorm Question: • Loops? • Counting? • Traversing the array? 1 2 3 4 5 6 II 0 IIII I 0 III
Example Count the number of elements (vector) Assume this array of dices (values 1 through 6 only) INDEX: (1) (2) (3) (4) length(array) number count dieNb dieNb dieNb I I 1 2 3 4 5 6 • How many times did we “traverse the array”? • How many times will we loop? • Which loop will we use? • Will there be nested loops? • How does counting works? 0 I I k k k k k k
Example Count the number of elements (vector)
Traversing up till a condition is met • The for loop is great if the entire array needs to be traversed • What if… • Traverse only until a condition is met? • Traverse only until an item is found? • For example • Linear search: search 1 by 1 • Binary search: items are sorted, jump around (i.e. phone book)
Example4 Linear Search (Vector) Assume this array of dices (values 1 through 6 only) Have I rolled at least one 5?
Key Ideas • New functions • length() • size() • numel() • To traverse an entire array: use the for loop • To traverse an array up till a condition is met: use the while loop, though each criteria are still present • Start at index 1 (or at r=1, c=1) • Increment to the next index/indices (somewhere) • Indicate where to stop if search criteria not met • You may have to nest two while loops is array is a matrix!