Q:

Control order of printing and figures in MATLAB 'publish' function

I have a simple MATLAB script which prints some text and displays figures in a loop, for example
for i = 1:3

    x = randn(100, 1);

    fprintf('Mean = %.2f\n', mean(x));
    fprintf('Std  = %.2f\n', std(x));

    figure;
    plot(cumsum(x));

end

I want to use the publish function to create a HTML file containing the output of this script, with the text and figures interleaved as they are in the loop, i.e. they order that they appear in the output should be

Text from the first loop run
Figures from the first loop run
Text from the second loop run
Figures from the second loop run
Text from the third loop run
Figures from the third loop run

However, the output currently appears in the following order

Text from the first loop run
Text from the second loop run
Text from the third loop run
Figures from the first loop run
Figures from the second loop run
Figures from the third loop run

How can I achieve the desired output?

A:

Within the loop, just before the end, include the command snapnow. That will force the publishing routine to take the snapshot there and then, rather than waiting for the end of the loop to collect all the images.

