在 Matlab 中创建连续输出

Creating Continuous Output in Matlab

我有一个类似这样的脚本:

i = 1;
while i <10000
   a = input('enter a ');
   c(i) = a;
   i = i + 1;

end

我试图让 'a' 大约每秒保存在 'c' 中,无论用户输入值需要多长时间或循环中发生的任何其他事情。因此,例如,假设用户为 'a' 输入 3 等待 2 秒,然后为 'a' 输入 6 然后等待 3 秒然后输入 12 然后有一段时间没有任何内容,'c' 看起来像这个:

c = 3 3 6 6 6 12 12 12 12 12...

现在,'c' 看起来像这样:

c = 3 6 12...

这不是我想要的。有什么建议么?它不一定是点上的一秒钟,但我想要连续输出。

你的问题很有趣,但不是很明确。我假设如下:

  • 每个输入都应立即附加c,并重复每秒再次附加,直到输入新值, 重置时间计数。从你的问题中不清楚你是否想要新输入的初始、固定 "commit" 到 c
  • 根据您对现已删除的问题的评论,您希望自动显示更新的c你应该在你的问题中说明这一点

然后,您可以使用一个 timer 对象 ,它会在输入每个新输入值时停止并重新启动。定时器配置为每秒唤醒一次。当它醒来时,它将最新的输入值 a 附加到矢量 c 并显示它。当不再需要时,应注意停止和删除计时器。此外,

  • 我正在考虑 空输入作为退出信号;也就是说,空输入表示用户想要完成,即使迭代还没有用完。使用 Ctrl-C 中止输入是不可行的,因为计时器会保持 运行ning。我不知道如何拦截 Ctrl-C.

  • 从输入函数input中删除提示字符串,因为它会干扰更新后c的自动显示]向量。

  • 用户输入阻止程序执行。如果您希望在计时器更新时使用 c 完成其他操作,请将它们包含在其 'TimerFcn' 函数中。目前该功能只是 'c = [c a]; disp(c)'(附加输入并显示它)。

代码

c = []; % initiallize
t = timer('ExecutionMode', 'fixedRate', ... % Work periodically
    'Period', 1, ... % Every 1 second...
    'TimerFcn', 'c = [c a]; disp(c)', ... % ... append latest value to c
    'ErrorFcn', 'delete(t)'); % If user ends with Ctrl-C, delete the timer
i = 1;
done = false;
clc % clear screen
while i < 10 & ~done
    a = input(''); % Input new value. No prompt string
    stop(t) % stop appending previous a
    if isempty(a)
        done = true; % no more iterations will not be run
    else
        start(t) % start timer: appends current a, and repeats every second
    end
    i = i + 1;
end
delete(t) % stop and delete timer
clear t % remove timer from workspace

例子

这是一个带有示例 运行 的 gif,我在其中输入具有不同暂停时间的值 10203040 ,并以空输入退出。