Friday, November 2, 2007

Matlab VII

While loops


Welcome back to another exciting installment of Matlab Tutorial, I hope you all had a good week. Have you mastered your skills on for loops yet? Well here is another command that is very similar to a for loop, in the sense that it is a continuous command that repeats steps that are specified and outputs certain data. The biggest difference that a while loop has over a for loop is the use of it. Instead of running through a loop with a given number of times and increments, the while loop continues to run until given parameters are unsatified. This is very useful but if used or written improperly will cause your program to run an infinite number of times. So as a warning up front, double check your code and syntax so the while loop doesn't go on forever.





So the first thing that needs to be established is when you want your while loop to run. It is a good tool to use when you want to cap off the number of times a loop runs through the data you have given the program. For instance, if you have a vector of 100 values, and you only want to sum up the first 20 terms, then a while loop can know to add up all of the X terms until X (index) > 20. After you get to the 21st term, the statement stated is false, and the loop stops. This example is written like this:
X = [3, 34, 87, 12,..., 3043]
Y = 1
Sum = 0
while Y <= 20
Sum = Sum + X(Y)
Y = Y + 1
end
Sum



This while loop goes through the first time knowing Y to be one and Sum to be zero. It fits the while loop's conditions, so it then proceeds to add the sum and the 1st term of X as the new value of Sum. It then adds one to Y and goes to the beginning of the loop. With Y = 2, the while loop goes through the same process. It will continue to add of each term of X until Y is 21, where the condition isn't met, so the loop stops and the next command under the loop is then performed. Our example loop just displays the last sum created of the first 20 terms of X.



The while loop can be a good tool when you don't know exactly how many times the loop must run. Make sure to add a line of code telling the value(s) in the condition statement to increment somehow, other wise it will run forever as I had done just now as I made sure the loop I created indeed works (Call me out if I want a syntax error). I hope you all are successful and have a good weekend. Stay tune for more from your favorite Matlab Tutorial!


Resources: While Loop Help with Cyclismo, HTML Tags at Web Source

No comments: