Progress indication

From NA-Wiki

Jump to: navigation, search

First example

In a Matlab computation it is sometimes nice to have some kind of progress indicator. This example shows how to make a progress indicator in the command window that does not scroll the screen (but overwrites the line from the previous progress message instead).

N = 175;
n = 8;
for j = n:N+n
    [x y z] = peaks(j);
    mesh(x,y,z), drawnow
    fprintf('                                     \r');
    fprintf('   j = %d \t ( %d%% )\r',j,round(100*(j-n)/N))
end
fprintf('\n')

Note that the fprintf statement works the same way in Matlab as it does in C (and is superior to disp)

Second example (least square polynomial fitting)

function eta = update_eta(this_step,eta)
%UPDATE_ETA  Update the ETA structure according to the current wall clock time
%   ETA = UPDATE_ETA(ETA)
%
%   Code example:
%
%       eta.last_step = ...;        % total number of time steps
%       eta.steps_per_update = ...; % time steps per update
%
%       while condition
%           % do some computations
%           eta = update_eta(eta);
%           if ~isnan(eta.tleft)
%                   fprintf('[%s, %s, %6ds, %6.2f%%] ...\n', ...
%                           datestr(now,31), datestr(now+eta.tleft/1e5,31), ...
%                           round(eta.tleft), eta.percent_done, ...);
%           end
%       end

%   Henrik Holst
%   Sun, 21 Sep 2008 21:17:52 +0200

fn = fieldnames(eta);
if ~ismember('tval',fn), eta.tval = []; end
if ~ismember('nval',fn), eta.nval = []; end
if ~ismember('max_nval',fn), eta.max_nval = 20; end
if ~ismember('poly_deg',fn), eta.poly_deg = 3; end
eta.this_step = this_step;
eta.tnow = rem(now,1)*1e5;
if length(eta.nval) < eta.max_nval
	eta.tval = [eta.tval;eta.tnow];
	eta.nval = [eta.nval;eta.this_step/eta.steps_per_update];
else
	eta.tval = [eta.tval(2:end);eta.tnow];
	eta.nval = [eta.nval(2:end);eta.this_step/eta.steps_per_update];
end
if length(eta.nval) >= eta.poly_deg+1
	A = zeros(length(eta.nval),eta.poly_deg+1);
	for k = 1:eta.poly_deg+1
		A(:,k) = eta.nval.^(eta.poly_deg+1-k);
	end
	eta.poly = A\eta.tval;
else
	eta.poly = nan(eta.poly_deg+1,1);
end
eta.steps_left = eta.last_step - eta.this_step;
eta.percent_done = 100*(1 - eta.steps_left/eta.last_step);
eta.tend = polyval(eta.poly,eta.last_step/eta.steps_per_update);
eta.tleft = eta.tend - eta.tnow;
Personal tools