I’d like to make a loop in Matlab that would work only over user specified intervals of time, instead of simply the whole time. How can one write this loop condition?
regards
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Generally you and iterate multiple ways. There are two main ways that I can think of off the top of my head. I will also open this up for community wiki so others can just easily edit this as well.
First, using a simple
Forloop.The general syntax is
for index = 1:someValuesomeValuecan really be anything that is greater than1in this case. Many times it’s simply the last index value of a matrix you’re wanting to traverse.You can modify this as well though! Let’s say you want every 3rd index starting with the 2nd position in the matrix. All you have to do is:
for index = 2:3:someValueThe 3 here tells the loop that it should add 3 to theindexat the end of each loop iteration until you get to (or surpass)someValue.Yet another modfication is traversing backwards. In this case you start at the ‘end’ and move to the beginning. It would look like this:
for index = someValue:-1:1You can also do every 4th index while going backwardsfor index = someValue:-4:1.Obviously you can replace the value between the two
:to be a step size that you want. You just have to be aware of potential indexing issues that can arrise. Namely trying to index out of bounds of the matrix or potentially going negative.Secondly here you can modify the value within the loop itself. Generally this isn’t the best idea when you’re using a
forloop as the value of your indexing variable will be changed by the loop as well as by you within the loop. Many times you’ll see this done with awhileloop or ado whilecombo.A few examples are as follows:
In the above example the loop will continue to loop until the index value
indexbecomes greater than or equal tosomeValueat the end of the current iteration of the loop. This type of loop will ALWAYS, and I repeat ALWAYS execute at least once.In this case the loop will continue to loop while
indexsatisfies the logical statement here. If the statement isn’t true when you try to run the loop for the first time it will not execute at all.Hope this helps and feel free to ask for any additional clarification if you want it!
Others, please feel free to edit to add additional information or clean up what I might have not explained fully =)