MATLAB is super efficient and fast at many things, but sometimes a computationally-intensive script or function can take a while to run. And, sometimes you wonder if it’s taking so long because of a bug and not because it’s just working hard.
Wouldn’t it be great to have some sort of indication of the progress being made?
Well, fortunately MATLAB has a convenient function for creating a progress bar: waitbar()
!
See the code snippet below (which you can get from the [GitHub repository] for an example of how to use the waitbar()
function to display progress with a lengthy calculation:
The Taylor series expansion of the exponential function:
\[e^x \simeq f\left( x \right) = \sum_{i=0}^{lim} \frac{x^i}{i!}\]%% MATLAB snippet to calculate Taylor expansion of the exponential
%% function highlighting use of 'waitbar()' to generate a progress bar
lim = 5000; % # of terms in expansion
x = 0.2; % value of exponent
taylor = 0;
f = waitbar(0,'Progress'); % establish progress bar
for i = 0:lim
waitbar(i/lim,f,'Progress'); % update progress bar
taylor = taylor + x^i/factorial(i); % add term to expansion
end
close(f) % close progress bar
When the code is run, a window pops up showing the progress of the for loop:
To use waitbar()
, we must first initialize it and assign it a handle so that we can refer to it later. In the example, we assign the handle to the variable f
. The text string, 'Progress'
, is what is to be displayed in the progress bar window:
f = waitbar(0,'Progress'); % establish progress bar
Then, any time we want to update the progress bar we call waitbar()
again using the handle:
waitbar(i/lim,f,'Progress'); % update progress bar
Finally, when we are done with the calculation we close the progress bar window:
close(f) % close progress bar
Note that using 5,000 terms in this expansion is overkill. It approximates the true value of $e^{0.2}$ (= 1.2214) with an error of less than $10^{-17}$! But using this many terms takes long enough (2.9 seconds on my computer - wonder how I timed that in MATLAB? check out this blog post) that we can visualize the progress bar changing.
How many terms would be required to get an answer that is only within $10^{-7}$?
Read more at the official MathWorks documentation for the waitbar() function.