MATLAB While Loop (Week 7)

 

Genaro Rivera

October 25, 2022

MATLAB While Loop (Week 7)

While Loop

This week, I focused on the while loop. A while loop repeats until a condition is met. The best way to think about coding is by visualizing yourself talking to someone. For example, above, you are saying “X is one. While X is less than 5, add 1 to it. If x is below 5, keep adding 1 to it.” Eventually, x becomes 5 which is where the loop ends. However, infinite loops exist as seen below.

Here, x will always be less than 5; if you keep subtracting 1 from 1, it will never be greater than or equal to 5. The picture on the left displays the output (AKA the command window). The command window rapidly subtracts 1 for ever until you stop it by pressing control c; I stopped it at -214106. In conclusion, while loops repeat until a condition is met. However, if the condition is never met, the loop repeats forever.

While Loop and For Loops Differences



Here, both functions do the same thing, but the for loop is better. The for loop goes through its procedure. ff is 1. Additionally, z will go from 1 to 5 (1:5). z will equal 1, go through the loop, equal 2, go through the loop, and repeat until it reaches 5 before ending, so the loop repeats 5 times. The while loop goes through its procedure. ff and z are 1. The condition says that as long z is 5 or below the loop will repeat. ff will be ff*z, z will increase by 1, ff will be ff*the new value of z, z will increase by 1 again, and repeat until z exceeds 5, so it repeats 5 times. The end results are both 120. Since you know that the loop will repeat 5 times, the for loop is more useful: just say 1:5.

Here, both functions do the same thing, but the while loop is better. The for loop goes through its procedure. ff is 3. ff doubles 400,000 times, but if ff is greater than or equal to 30, the loop ends. In the for loop, we do not know how many steps it will take before 3 is greater than or equal to 30, so to play it safe, we include 400,000 steps. The while loop goes through its procedure. ff is 3. While ff is less than 25, MATLAB will double ff. Again, we do not know how many steps it will take before ff is greater than or equal to 30, and for the while loop, we do not need to know making it the better of the two functions. If you know the number of steps, use the for loop; if you do not know the number of steps, use the while loop.







Comments

Popular posts from this blog

Weather Balloon Spring Flight

System Block Diagrams Introduction Week 5

Temperature Sensor week 8