Execute for loop with time

I have a for loop like this

for t = 0: 1: 60
    // my code
end

I want to execute my code in 1st, 2nd, 3rd, ..., 60th seconds. How to do this? Also how can I run my code at arbitrary times? For example in 1st, 3rd and 10th seconds?

Answers


What you can do is use the pause command and place how many seconds you want your code to pause for. Once you do that, you execute the code that you want. As an example:

times = 1:60;
for t = [times(1), diff(times)]
    pause(t); % // Pause for t seconds
    %// Place your code here...
    ...
    ...
end

As noted by @CST-Link, we should not take elapsed time into account, which is why we take the difference in neighbouring times of when you want to start your loop so that we can start your code as quickly as we can.

Also, if you want arbitrary times, place all of your times in an array, then loop through the array.

times = [1 3 10];
for t = [times(1), diff(times)]
    pause(t); %// Pause for t seconds
    %// Place your code here...
    ...
    ...
end 

Need Your Help

Convert Vector<int> to String

c++ string vector

I want to make a program that first input array of string, then convert it into integer, and then push it to a vector.

How to call different associated resource variables in their controllers?

ruby-on-rails ruby

I am a beginner learning Ruby on Rails. Apologies if this question is very obvious...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.