14-440-127 Lecture 6 Notes

14-440-127 Lecture 6 Notes - 14:440:127 Introduction to...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
14:440:127– Introduction to Computers for Engineers Notes for Lecture 6 Rutgers University, Fall 2008 Instructor- Blase E. Ur 1 Loops One of the things computers are very good at is doing repetitive tasks. Even better than repetitive tasks, computers are excellent at performing tasks over and over that are slightly different than each other. 1.1 For Loops Sometimes, you’ll know exactly how many times you need to perform some action. Take the fol- lowing example: ”Display the numbers from 1 to 100, individually.” Rather than type ( disp(1); disp(2); disp(3). ..) and so on, you could just use a for loop. A for loop lets you specify that Matlab perform some repetitive action over and over, changing one variable each time. Here’s the syntax: for i = VECTOR % replace capitalized parts STATEMENTS % replace capitalized parts end for i = 1:100 disp(i) end The for loop must begin with the word for , and end with the word end . You must also specify some variable, here called i , that is known as the index. The first time you go through the loop, i will be 1. The next time you go through the loop, i will be 2, and so on, until the loop runs one final time with i equal to 100. 1.1.1 Examples of For Loops In a simple example, let’s use a for loop that sums the numbers from 1 to 100: s = 0; for z = 1:100 s = s+z; end disp(z)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Now, what if we wanted to write a for loop that mirrors the max function on a vector V ? maxvalue = -inf; location = -1; for x = 1:length(V) if(V(x)>maxvalue) maxvalue = V(x); location = x; end end disp(maxvalue) disp(location) However, since we have more control over the exact functionality, we can tweak the way this program operates. Let’s say we wanted it to find all locations where the maximum appears in the vector. Let’s first plan at our attack in pseudocode (a Matlab-English hybrid): Set maxvalue to be -inf Create an empty vector of locations Say that we have found 0 locations (we will use this variable to locate the end of location) For each element in V: If that element is greater than our current maxvalue Erase all of the previous locations Add the current location Set the maxvalue to be the current value Otherwise, if that element equals the maxvalue Add that location to our vector
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

14-440-127 Lecture 6 Notes - 14:440:127 Introduction to...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online