A blog by Rob J Hyndman 

Twitter Gplus RSS

LaTeX loops

Published on 23 October 2012

Today I was writ­ing a report which included 20 fig­ures, with the names demandplot1.pdf, demandplot2.pdf, …, demandplot20.pdf, and all with sim­i­lar cap­tions. Clearly a loop was required. After all, LaTeX is a pro­gram­ming lan­guage, so we should be able to take advan­tage of its capabilities.

I found the for­loop pack­age which han­dled the prob­lem per­fectly. My first attempt looked like this:

\caption{Hourly demand (GW) for zone #1.}

The magic hap­pens in the last line pro­vid­ing a loop from 1 to 20, gen­er­at­ing the com­mands \demandplot{1}, \demandplot{2}, …, \demandplot{20}.

How­ever, that didn’t work. After exam­in­ing the log file, it seems that LaTeX can’t han­dle 20 fig­ures in a row as it has to store them up while it looks for where to place them. So the fol­low­ing mod­i­fied code was used:

\caption{Hourly demand (GW) for zone #1.}

This loops from 1 to 10, then the \clearpage com­mand processes all floats before pro­ceed­ing with the loop from 11 to 20.

Any time you need some repet­i­tive code in LaTeX, the for­loop pack­age should make your life eas­ier (and make silly mis­takes less likely).

Related Posts:

2 Comments  comments 
  • http://www.facebook.com/prashanth.chengi Prashanth Chengi

    Wow! Thanks so very much! It’s cer­tainly going to come in handy for me!

  • Robert

    Last time I
    faced with the same prob­lem — almost 40 fig­ures I had to put into my report.
    Because names of those fig­ures dif­fered not only in a sin­gle num­ber so I wrote
    a very sim­ple R code. Quick and easy way but prob­a­bly less ele­gant then your
    approach. That’s why I like read your blog it’s very help­ful. [By the way I
    look for­ward to watch­ing a video: Sim­pleR tricks and tools].