所以我有一个for循环,在每次迭代时,我想显示格式化的文本以及一些数字。通常,我们可以使用disp或fprintf,但我想要做的是,命令窗口的相同部分输出文本/数字,只是覆盖旧的输出。
我怎么能做到呢?我在其他一些程序中见过,所以我知道这是可能的,但不是怎么做到的。
例如,在for-循环的第一次迭代中,我希望在命令提示符上输出:
>> Measurement1 : 0.33 0.23 0.34 -32.32
Measurement2 : 433.2
Text Stuff : 'The cat who ate the rat'现在,在循环的第二次迭代中,我不想要新行或新行,我只是想替换旧数字和旧文本,在命令窗口的相同位置。因此,在第二次迭代中,我可能会得到以下内容:
>> Measurement1 : -132.3 32.1 32.23 -320.32
Measurement2 : 3.2
Text Stuff : 'The dog who ate the cat'谢谢
发布于 2012-09-03 15:56:24
下面是你要找的东西的一个例子:
%# Generate the data
Measurement1 = {[0.33 0.23 0.34 -32.32]; [-132.3 32.1 32.23 -320.32]};
Measurement2 = {433.2; 3.2};
TextStuff = {'The cat who ate the rat'; 'The dog who ate the cat'};
s = cell2struct([Measurement1, Measurement2, TextStuff], ...
{'Measurement1', 'Measurement2', 'TextStuff'}, 2);
str_format = @(tag, value)sprintf('%s:%s', tag, value);
%# Iterate over the data and print it on the same figure
figure
for i = 1:length(s)
%# Clear the figure
clf, set(gcf, 'color', 'white'), axis off
%# Output the data
text(0, 1, str_format('Measurement1', num2str(s(i).Measurement1)));
text(0, 0.9, str_format('Measurement2', num2str(s(i).Measurement2)));
text(0, 0.8, str_format('TextStuff', s(i).TextStuff))
%# Wait until the uses press a key
pause
end注意,pause强制您在执行下一次迭代之前按下一个键。我把它放在那里,这样你就有机会在每次迭代中看到这个数字。
P.S
基于这个答案 (关于您的另一个问题),您还可以输出LaTex方程。
编辑-一些更多的解释:
cell2struct是将单元格数组转换为结构数组的函数。在您的示例中,有Measurement1、Measurement2和TextStuff,每个单元格数组都包含不同字段的数据。
所有单元格阵列都统一为一个单元阵列数组:[Measurement1, Measurement2, TextStuff]。cell2struct从每个单元格数组中获取每一行并形成一个结构,其结果存储为一个结构数组,如下所示:
s =
2x1 struct array with fields:
Measurement1
Measurement2
TextStuff可以使用s(1)提取第一组值,使用s(2)提取第二组值,依此类推。例如,s(1).TextStuff为您提供了'The cat who ate the rat'。
我建议您在MATLAB命令提示符中键入s以查看其内容。
helper函数str_format是我创建的一个匿名函数,用于格式化每个字段的输出字符串。它的输入参数是tag (字段名字符串)和value (字段值字符串),它们使用sprintf命令连接在一起,类似于C/C++中的sprintf函数。
发布于 2012-09-03 15:58:06
这文章指出,您可以使用backspace来完成这个任务,尽管它似乎也表明它不能处理多行。
原则是,每次迭代时,您都要输出足够多的退空字符,以便将光标移动到输出的开头,然后开始在旧的基础上编写新的输出。在来回移动光标时,您必须跟踪光标的位置。
发布于 2013-12-12 10:22:50
我就是为了这个目的使用“dispstat”函数的。它可以更新先前的输出,这是默认的“disp”缺少的函数。使用起来很简单。它可以从这里下载:http://www.mathworks.com/matlabcentral/fileexchange/44673-overwritable-message-outputs-to-commandline-window
*样本使用情况:
dispstat('','init'); % One time only initialization
dispstat(sprintf('Begining the process...'),'keepthis','timestamp');
for i = 97:100
dispstat(sprintf('Progress %d%%',i),'timestamp');
%doing some heavy stuff here
end
dispstat('Finished.','keepprev');*产出:
11:25:37 Begining the process...
11:25:37 Progress 100%
Finished.万事如意
https://stackoverflow.com/questions/12249579
复制相似问题