如何监控长计算?

Ist*_*har 5 iteration matlab user-interface printf

我想建立一个计数器,告诉我一个长迭代计算(例如in for).

是否可以设置此计数器,当它在屏幕上更新时,它会替换以前的值?

也就是说,打印a的迭代器变量for是不行的,因为Matlab要么将它打印到新行,要么在之前的值之后打印,但是在10000次迭代之后,屏幕将以任一方式填充.另外,我想在每个回合更新计数器.

Oli*_*rth 5

您可以使用\b打印退格符.例如:

for i=1:10
    fprintf(1, '\b%d', i);
end
Run Code Online (Sandbox Code Playgroud)

  • @Simon:你应该大声说出10,并把它作为最高号码. (3认同)

Sim*_*mon 5

fprintf('\n')
for i=1:15
    fprintf([repmat('\b', 1, length(num2str(i-1))) '%d'], i)
    pause(0.1)
end
fprintf('\n')
Run Code Online (Sandbox Code Playgroud)


Ian*_*cks 5

我不久前做了这个功能,它绘制了一个漂亮的ascii进度条.与你问题的其他两个答案基本相同,但更多的打包

function progressbar(percent, N, init, extrastr)
% Draws a progress bar in the matlab command prompt. Useful for lengthly
% calculations using for loops
%
% Arguments:
%   - percent:  A number between 0 and 1
%   - N:        how many characters wide the bar should be
%   - init:     (optional; default false) true or false; whether or not
%               this is the first time calling the progressbar function for
%               your current bar.
%   - extrastr: (optional; default char(10)) An extra string to append to
%               the progress bar. Things will go screwy at the command
%               console if this string changes length from call to call of
%               progressbar.
%
% Outputs:
%
% Usage Example:
%
%   for k=1:1000
%       progressbar(k/1000,50,k==1,sprintf('\n We are are on number%4d\n', k));
%       % fake a computation
%       pause(0.05);
%   end
%

    if nargin < 3
        init = 0;
    end
    if nargin < 4
        extrastr = char(10);
    end

    percent = min(max(real(percent),0),1);

    done = round(N*percent);
    done_str = '*'*ones(1, done);
    left_str = '-'*ones(1, N-done);
    bar = sprintf(['||' done_str left_str '|| %3d'],round(percent*100));

    erase = [];
    if ~init
        % use backspace characters to erase the previously drawn bar
        erase = ['' char(8)*ones(1,length(bar)+length(extrastr)+1)];
    end

    fprintf([erase bar '%s' extrastr], '%');
    drawnow;

end
Run Code Online (Sandbox Code Playgroud)

如果你的for循环是巨大的,并且每次传递很短,它将增加大量的开销计算时间,因此只需要每100次循环迭代调用它,或者根据需要调用它.