随时间执行循环

Dan*_*nte 3 matlab for-loop timer

我有这样的for循环

for t = 0: 1: 60
    // my code
end
Run Code Online (Sandbox Code Playgroud)

我想在第1,第2,第3,......,第60秒执行我的代码.这该怎么做?另外我如何在任意时间运行我的代码?例如在第1秒,第3秒和第10秒?

ray*_*ica 5

您可以做的是使用该pause命令并将您希望代码的秒数pause放置.完成后,执行所需的代码.举个例子:

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

正如@ CST-Link所指出的那样,我们不应该考虑经过的时间,这就是为什么我们在你想要开始循环的相邻时间中采取差异,以便我们可以尽快开始你的代码.

此外,如果您想要任意时间,请将所有时间放在一个数组中,然后遍历数组.

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


小智 5

轮询很糟糕,但 Matlab 默认是单线程的,所以......

对于第一种情况:

tic;
for t = 1:60
    while toc < t, pause(0.01); end;
    % your code
end;
Run Code Online (Sandbox Code Playgroud)

对于第二种情况:

tic;
for t = [1,3,10]
    while toc < t, pause(0.01); end;
    % your code
end;
Run Code Online (Sandbox Code Playgroud)

这些pause电话是在Amro对忙等待的明智观察之后添加的。0.01 秒听起来像是计时精度和旋转“数量”之间的一个很好的交易......