Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
Dante Avatar asked Dec 08 '22 07:12

Dante


1 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 
like image 121
rayryeng Avatar answered Dec 17 '22 05:12

rayryeng