jwm
jwm

Reputation: 5030

Matlab how to show progress in text showing up in command window

I am running a program that needs to take some time. It is better to show the running progress in real time, showing up in the command window. Something like below:

>>>>>>>> completed 90%

Assume the program runs though multiple loops:

for ii = 1:n
    for jj = 1:m
        for kk = 1:s
            .....
        end
    end
end

Is there any efficient way or some special function to achieve that? I don't want to use waitbar.m since I also have other results printed in real time in the command window. These printed results, coupled with the texted progress, are used for the convenience of inspection.

Upvotes: 0

Views: 1257

Answers (2)

UJIN
UJIN

Reputation: 1758

First of all you need to compute the percentage step every time the inner loop advances. This can be done by computing:

percent_step = 1.0 / n / m / s

Then you can just force MATLAB to print on the same line by using a concatenation of \b (backspace character). Here is a MWE that just compute a random 10x10 matrix and get its transpose (just to show the percentage progress):

backspaces = '';
percentage = 0;

% DEFINE n, m, s as you wish, here I put some random values
n = 100;
m = 15;
s = 24;

percent_step = 100.0 / n / m / s;

for ii = 1:n
    for jj = 1:m
        for kk = 1:s

            % Do stuff
            a = rand(10);
            b = a';

            % Print percentage progress
            percentage = percentage + percent_step;
            perc_str = sprintf('completed %3.1f', percentage);
            fprintf([backspaces, perc_str]);
            backspaces = repmat(sprintf('\b'), 1, length(perc_str));

        end
    end
end

Upvotes: 3

paisanco
paisanco

Reputation: 4164

If you don't mind a progress display opening up in a separate window, you could use the Matlab waitbar.

For your example, say you wanted to compute a waitbar based on the number of iterations completed over the outer loop, it would be something like

h=waitbar(0, 'My waitbar');

for ii = 1:n
    for jj = 1:m
        for kk = 1:s
            .....
        end
    end
    fraction_done = ii/n;
    waitbar(fraction_done)
end

close (h)

If you really want a text-based display, there is the waittext available on MATLAB File Exchange at https://www.mathworks.com/matlabcentral/fileexchange/56424-waittext.

I have not worked with this but it appears to be similar to what you wanted.

Upvotes: 1

Related Questions