traversing an array 1.definition 2.use the for loop 3.some new functions 4.use the while loop 1
TRANSCRIPT
2
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
3
Most practical loop
• The loop used to traverse an array: for
• Applied to a vectorfor k = 1:__
%codeend
• Applied to a matrixfor r = 1:__
for c = 1:__ %codeend
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.
4
Helpful functions
• How many elements are in the array?
Function Return value
length(vector) Number of elements in the vector
length(matrix) Highest dimension
size(matrix,1) Number of rows in the matrix
size(matrix,2) Number of columns in the matrix
size(matrix,n) Size in the nth dimension
numel(array) Number of elements total in the array
7
Example2 Find the minimum (in a matrix)
• Nested loops
(1)
(2)
(3)
(4)
(5)
(1) (2) (3) (4) (5) (6) (7)
r
c c c c c c c
r
8
Example3 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
3 1 3 6 6 3 3 6 3 4 1
number count
II0IIIII0III
123456
Brainstorm Question:-Loops?-Counting?-Traversing the array?
9
Example3 Count the number of elements (vector)
• Assume this array of dices (values 1 through 6 only)
3 1 3 6 6 3 3 6 3 4 1
number count
IdieNbdieNb
k k k k k
INDEX: (1) (2) (3) (4) length(array)
k
123456
I0
dieNb II•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?
11
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?– Of course the _________ loop is used!
• For example– Linear search: search 1 by 1– Binary search: items are sorted, jump around (i.e. phone book)
12
Example4 Linear Search (Vector)
• Assume this array of dices (values 1 through 6 only)
• Have I rolled at least one 5?
13
Lessons Learned
• 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!