Storing and recalling variable number of text strings in LaTeX - latex

I'm currently writing an API document in LaTeX. I have a tabular environment with a list of error codes and descriptions, like so:
\begin{tabular}{|c|l|}
\hline
\textbf{Code} & \textbf{Description} \\ \hline
1 & (description of error 1) \\ \hline
2 & (description of error 2) \\ \hline
\end{tabular}
At various places later in the document, I reference an error's code and its description together, like so:
Possible error conditions:
\begin{itemize}
\item 1---(description of error 1)
\end{itemize}
I want to automate this process so I don't have to retype the descriptions every time. I have tried using a counter, labels, and the \savebox command, but it's pretty cumbersome:
\newcounter{error}
% Inside the tabular environment:
\newsavebox{\ErrorOne}
\savebox{\ErrorOne}{(description of error 1)}
\refstepcounter{error} \label{ErrorOne} \arabic{error} & \usebox{\ErrorOne} \\ \hline
and later, to reference the error,
\ref{ErrorOne}---\usebox{\ErrorOne}
I particularly object to having to use ErrorOne for the labels but \ErrorOne (with the leading backslash) for the saveboxes. I also don't really want names like ErrorOne, since I might need to change the order at some point. What I want is to be able to define a few commands:
\newerror{errorlabel}{Description} % defines the error (doesn't output anything)
\errorcode{errorlabel} % outputs the error code
\errordesc{errorlabel} % outputs the error description
and then be able to say something like
\newerror{ArgumentError}{Too many arguments}
\newerror{DatabaseError}{Could not connect to database}
% Inside the tabular environment:
\errorcode{ArgumentError} & \errordesc{ArgumentError} \\ \hline
\errorcode{DatabaseError} & \errordesc{DatabaseError} \\ \hline
% Later on:
\errorcode{DatabaseError}---\errordesc{DatabaseError}
with the error codes (1, 2, 3, ...) being automatically generated like labels would be.
Any ideas?

The following works for me
\catcode`\#=11
\newcounter{error}
\def\newerror#1#2{\refstepcounter{error}%
\expandafter\xdef\csname errno##1\endcsname{\arabic{error}}%
\expandafter\xdef\csname errds##1\endcsname{#2}%
}
\def\errorcode#1{\expandafter\printerrinfo \csname errno##1\endcsname}
\def\errordesc#1{\expandafter\printerrinfo \csname errds##1\endcsname}
\def\printerrinfo#1{\ifx#1\relax\errmessage{Error code is invalid}%
\else\expandafter#1\fi}
\catcode`\#=12
\newerror{ArgumentError}{Too many arguments}
\newerror{DatabaseError}{Could not connect to database}
\errorcode{DatabaseError}---\errordesc{DatabaseError}

In your preamble, create new commands for each error, then just call the command:
\newcommand{\errorone}{this is the error and its description}
then in the body, just call the new command:
\begin{tabular}{|c|l|}
\hline
\textbf{Code} & \textbf{Description} \\ \hline
1 & \errorone \\ \hline

Related

Table caption misplaced and no list of tables generated

I am writing an APA-style document in RMarkdown using Papaya package, which compiles into LaTeX, and then to pdf, by pandoc. I know a small amout of LaTeX, and I am not familiar with RMarkdown, and was asked to use it. So I have two problems here, and thank you in advance for any help. The problems might be related to Rmarkdown/Papaya, but they could also be purely LaTeX related, so even if you don't know about RMarkdown, you may still know something.
The first problem. I have the following table in my RMarkdown file,
\begin{center}
\begin{tabular}{| c | c | c | c | c | c | c |}
\hline
Model & Composability & Unboundness & Comm. & Sync. & Distribution & Mobility\\ \hline
$\pi$ & explicit & explicit & shared-mem & sync & NA & NA \\ \hline
Join & explicit & implicit & shared-mem & sync & implicit & implicit\\ \hline
Ambient & explicit & explicit & shared-mem & sync & explicit & explicit\\ \hline
Actor & NA & implicit & message-pass & async & implicit & implicit \\ \hline
\end{tabular}
\captionof{table}{Summary of Properties of Concurrency Models}\label{summary}
\end{center}
I was wondering how I can make the caption one-line and centered in the generated pdf file? It now spans two lines and is not centered (see this screenshot).
The second problem. I also would like to generate a list of tables after tables of contents. When I add \listoftables to the beginning part of the RMarkdown file together with other LaTeX command, \listoftables is missing from the generated .tex file, but the other commands shown below such as \newcommand are preserved in the .tex file.
```{r analysis-preferences}
# Seed for random number generation
set.seed(42)
knitr::opts_chunk$set(cache.extra = knitr::rand_seed)
```
\listoftables
\newcommand{\defeq}{\vcentcolon=}
\newcounter{equationset}
\newcommand{\equationset}[1]{% \equationset{<caption>}
\refstepcounter{equationset}% Step counter
\noindent\makebox[\linewidth]{Equation set~\theequationset: #1}}
\lstset{
basicstyle=\ttfamily,
mathescape
}
Then I notice there is an option at the beginning of the RMarkdown file
tablelist : no
and I change it to
tablelist : yes
but I get the following new compilation warning:
Warning message:
Package tocloft Warning: \#starttoc has already been redefined; tocloft bailing
out. on input line 1147.
The LaTeX packages that I included in the RMarkdown file are:
header-includes:
- \usepackage{amsmath}
- \usepackage{mathtools}
- \usepackage{listings}
- \usepackage{caption}

Using MathJax I need a solution for \ensuremath

I'm using a MathJax in several projects and it generally works like a charm.
Today, however, I ran into a problem during the translation of a part of an existing LaTeX document with the following align-environment:
\begin{align}
& (\lambda x.(\lambda y.(\lambda z.xyz)))abc \\
= & \text{\{ impliciete toepassing expliciet maken \}} \\
& (((\lambda x.(\lambda y.(\lambda z.xyz)))a)b)c \\
= & \text{\{ \ensuremath{\beta}-reductie, substitutie van \ensuremath{x}door \ensuremath{a}\}} \\
& ((\lambda y.(\lambda z.ayz))b)c \\
= & \{\text{\ensuremath{\beta}-reductie, \ensuremath{y\,:=b}}\} \\
& (\lambda z.abz)c \\
= & \text{\{ \ensuremath{\beta}-reductie, \ensuremath{z\,:=c}} \\
& abc \\ \boxed{} \end{align}
The result rendered with LaTeX is this (sorry for the Dutch text ;-):
The align-environment is essentially a math context, so if you want text, you need to enclose that text with \text{...}. But when you need again math symbols within that text, you escape the text context by enclosing the maths with \ensuremath{...}.
And MathJax renders it like:
That Mathjax centers everything doesn't matter, that is something I can handle with CSS. But the rendering of \ensuremath is a problem. Clearly MathJax doesn't support \ensuremath, but I can't think of a workable workaround where I can use math symbols in a text-context.
Ideally I'ld like to have a solution using an alternative LaTeX construction (hence the cross listing)
Any ideas?
You should use $...$ or \(...\) in place of \ensuremath{...}. This seems more natural to me even in LaTeX itself (as \ensuremath is really designed for use within macros that might be used inside both text- and math-modes).
So you can do
\begin{align}
& (\lambda x.(\lambda y.(\lambda z.xyz)))abc \\
= & \{\text{ impliciete toepassing expliciet maken }\} \\
& (((\lambda x.(\lambda y.(\lambda z.xyz)))a)b)c \\
= & \{\text{ $\beta$-reductie, substitutie van $x$door $a$ }\} \\
& ((\lambda y.(\lambda z.ayz))b)c \\
= & \{\text{ $\beta$-reductie, $y:=b$ }\} \\
& (\lambda z.abz)c \\
= & \{\text{ $\beta$-reductie, $z:=c$ }\} \\
& abc \\ \boxed{} \end{align}
I also put the \{ and \} outside the \text{}, though you can do them inside if you prefer.
The centering is probably due to CSS on your page, as MathJax left-justifies these by default.

pandas dataframe as latex or html table nbconvert

Is it possible to get a nicely formatted table from a pandas dataframe in ipython notebook when using nbconvert to latex & PDF?
The default seems to be just a left-aligned block of numbers in a shoddy looking font.
I would like to have something more like the html display of dataframes in the notebook, or a latex table. Saving and displaying a .png image of an HTML rendered dataframe would also be fine, but how exactly to do that has proved elusive.
Minimally, I would just like a simple centre-aligned table in a nice font.
I haven't had any luck with various attempts to use the .to_latex() method to get latex tables from pandas dataframes, either within the notebook or in nbconvert outputs. I've also tried (after reading ipython dev list discussions, and following the custom display logic notebook example) making a custom class with _repr_html_ and _repr_latex_ methods, returning the results of _to_html() and _to_latex(), respectively. I think a main problem with the nb conversion is that pdflatex isn't happy with either the {'s or the //'s in the dataframe to_latex() output. But I don't want to start fiddling around with that before checking I haven't missed something.
Thanks.
There is a simpler approach that is discussed in this Github issue. Basically, you have to add a _repr_latex_ method to the DataFrame class, a procedure that is documented from pandas in their official documentation.
I did this in a notebook like this:
import pandas as pd
pd.set_option('display.notebook_repr_html', True)
def _repr_latex_(self):
return "\centering{%s}" % self.to_latex()
pd.DataFrame._repr_latex_ = _repr_latex_ # monkey patch pandas DataFrame
The following code:
d = {'one' : [1., 2., 3., 4.],
'two' : [4., 3., 2., 1.]}
df = pd.DataFrame(d)
df
turns into an HTML table if evaluated live in the notebook, and it converts into a (centered) table in PDF format:
$ ipython nbconvert --to latex --post PDF notebook.ipynb
I wrote my own mako-based template scheme for this. I think it's actually quite an easy workflow if you commit to chugging through it for yourself once. After that, you begin to see that templating the metadata of your desired format so it can be factored out of the code (and doesn't represent a third-party dependence) is a very nice way to solve it.
Here is the workflow I came up with.
Write the .mako template that accepts your dataframe as an argument (and possibly other args) and converts it to the TeX format you want (example below).
Make a wrapper class (I call it to_tex) that makes the API you desire (e.g. so you can pass it your data objects and it handles the call to mako render commands internally).
Within the wraper class, decide on how you want the output. Print the TeX code to the screen? Use a subprocess to actually compile it to a pdf?
In my case, I was working on generating preliminary results for a research paper and needed to format tables into a complicated double-sorted structure with nested column names, etc. Here's an example of what one of the tables looks like:
Here is the mako template for this (warning, gross):
<%page args="df, table_title, group_var, sort_var"/>
<%
"""
Template for country/industry two-panel double sorts TeX table.
Inputs:
-------
df: pandas DataFrame
Must be 17 x 12 and have rows and columns that positionally
correspond to the entries of the table.
table_title: string
String used for the title of the table.
group_var: string
String naming the grouping variable for the horizontal sorts.
Should be 'Country' or 'Industry'.
sort_var: string (raw)
String naming the variable that is being sorted, e.g.
"beta" or "ivol". Note that if you want the symbol to
be rendered as a TeX symbol, then pass a raw Python
string as the arg and include the needed TeX markup in
the passed string. If the string isn't raw, some of the
TeX markup might be interpreted as special characters.
Returns:
--------
When used with mako.template.Template.render, will produce
a raw TeX string that can be rendered into a PDF containing
the specified data.
Author:
-------
Ely M. Spears, 05/21/2013
"""
# Python imports and helper function definitions.
import numpy as np
def format_helper(x):
return str(np.round(x,2))
%>
<%text>
\documentclass[10pt]{article}
\usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry}
\usepackage{array}
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\setlength{\parskip}{1em}
\setlength{\parindent}{0in}
\renewcommand*\arraystretch{1.5}
\author{Ely Spears}
\begin{document}
\begin{table} \caption{</%text>${table_title}<%text>}
\begin{center}
\begin{tabular}{ | p{2.5cm} c c c c c p{1cm} c c c c c c p{1cm} |}
\hline
& \multicolumn{6}{c}{CAPM $\beta$} & \multicolumn{6}{c}{CAPM $\alpha$ (\%p.a.)} & \\
\cline{2-7} \cline{9-14}
& \multicolumn{6}{c}{</%text>${group_var}<%text> </%text>${sort_var}<%text> is:} & \multicolumn{6}{c}{</%text>${group_var}<%text> </%text>${sort_var}<%text> is:} & \\
Stock </%text>${sort_var}<%text> is: & Low & 2 & 3 & 4 & High & Low - High & & Low & 2 & 3 & 4 & High & Low - High \\
\hline
\multicolumn{4}{|l}{Panel A. Point estimates} & & & & & & & & & & \\
\hline
Low & </%text>${' & '.join(df.ix[0].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[0].map(format_helper).values[6:])}<%text> \\
2 & </%text>${' & '.join(df.ix[1].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[1].map(format_helper).values[6:])}<%text> \\
3 & </%text>${' & '.join(df.ix[2].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[2].map(format_helper).values[6:])}<%text> \\
4 & </%text>${' & '.join(df.ix[3].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[3].map(format_helper).values[6:])}<%text> \\
High & </%text>${' & '.join(df.ix[4].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[4].map(format_helper).values[6:])}<%text> \\
Low - High & </%text>${' & '.join(df.ix[5].map(format_helper).values[0:5])}<%text> & & & </%text>${' & '.join(df.ix[5].map(format_helper).values[6:11])}<%text> & \\
\multicolumn{6}{|l}{</%text>${group_var}<%text> effect (average of Low - High \underline{column})}
& </%text>${format_helper(df.ix[6,5])}<%text> & & & & & & & </%text>${format_helper(df.ix[6,11])}<%text> \\
\multicolumn{6}{|l}{Within-</%text>${group_var}<%text> effect (average of Low - High \underline{row})}
& </%text>${format_helper(df.ix[7,5])}<%text> & & & & & & & </%text>${format_helper(df.ix[7,11])}<%text> \\
\multicolumn{13}{|l}{Total effect} & </%text>${format_helper(df.ix[8,11])}<%text> \\
\hline
\multicolumn{4}{|l}{Panel B. t-statistics} & & & & & & & & & & \\
\hline
Low & </%text>${' & '.join(df.ix[9].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[9].map(format_helper).values[6:])}<%text> \\
2 & </%text>${' & '.join(df.ix[10].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[10].map(format_helper).values[6:])}<%text> \\
3 & </%text>${' & '.join(df.ix[11].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[11].map(format_helper).values[6:])}<%text> \\
4 & </%text>${' & '.join(df.ix[12].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[12].map(format_helper).values[6:])}<%text> \\
High & </%text>${' & '.join(df.ix[13].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[13].map(format_helper).values[6:])}<%text> \\
Low - High & </%text>${' & '.join(df.ix[14].map(format_helper).values[0:5])}<%text> & & & </%text>${' & '.join(df.ix[14].map(format_helper).values[6:11])}<%text> & \\
\multicolumn{6}{|l}{</%text>${group_var}<%text> effect (average of Low - High \underline{column})}
& </%text>${format_helper(df.ix[15,5])}<%text> & & & & & & & </%text>${format_helper(df.ix[15,11])}<%text> \\
\multicolumn{6}{|l}{Within-</%text>${group_var}<%text> effect (average of Low - High \underline{row})}
& </%text>${format_helper(df.ix[16,5])}<%text> & & & & & & & </%text>${format_helper(df.ix[16,11])}<%text> \\
\hline
\end{tabular}
\end{center}
\end{table}
\end{document}
</%text>
My wrapper to_tex.py looks like this (with example usage in the if __name__ == "__main__" section):
"""
to_tex.py
Class for handling strings of TeX code and producing the
rendered PDF via PDF LaTeX. Assumes ability to call PDFLaTeX
via the operating system.
"""
class to_tex(object):
"""
Publishes a TeX string to a PDF rendering with pdflatex.
"""
def __init__(self, tex_string, tex_file, display=False):
"""
Publish a string to a .tex file, which will be
rendered into a .pdf file via pdflatex.
"""
self.tex_string = tex_string
self.tex_file = tex_file
self.__to_tex_file()
self.__to_pdf_file(display)
print "Render status:", self.render_status
def __to_tex_file(self):
"""
Writes a tex string to a file.
"""
with open(self.tex_file, 'w') as t_file:
t_file.write(self.tex_string)
def __to_pdf_file(self, display=False):
"""
Compile a tex file to a pdf file with the
same file path and name.
"""
try:
import os
from subprocess import Popen
proc = Popen(["pdflatex", "-output-directory", os.path.dirname(self.tex_file), self.tex_file])
proc.communicate()
self.render_status = "success"
except Exception as e:
self.render_status = str(e)
# Launch a display of the pdf if requested.
if (self.render_status == "success") and display:
try:
proc = Popen(["evince", self.tex_file.replace(".tex", ".pdf")])
proc.communicate()
except:
pass
if __name__ == "__main__":
from mako.template import Template
template_file = "path/to/template.mako"
t = Template(filename=template_file)
tex_str = t.render(arg1="arg1", ...)
tex_wrapper = to_tex(tex_str, )
My choice was to directly pump the TeX string to pdflatex and leave as an option to display it.
A small snippet of code actually using this with a DataFrame is here:
# Assume calculation work is done prior to this ...
all_beta = pandas.concat([beta_df, beta_tstat_df], axis=0)
all_alpha = pandas.concat([alpha_df, alpha_tstat_df], axis=0)
all_df = pandas.concat([all_beta, all_alpha], axis=1)
# Render result in TeX
tex_mako = "/my_project/templates/mako/two_panel_double_sort_table.mako"
tex_file = "/my_project/some_tex_file_name.tex"
from mako.template import Template
t = Template(filename=tex_mako)
tex_str = t.render(all_df, table_title, group_var, tex_risk_name)
import my_project.to_tex as to_tex
tex_obj = to_tex.to_tex(tex_str, tex_file)
The simplest way available now is to display your dataframe as a markdown table. You may need to install tabulate for this.
In your code cell, when displaying dataframe, use following:
from IPython.display import Markdown, display
display(Markdown(df.to_markdown()))
Since it is a markdown table, nbconvert can easily translate this into latex.

How do I compile a LaTeX table exported from R?

I'm completely new to LaTeX and have the MacTeX 2009 package installed, with the intent of having tables from R output into LaTeX and formatted as PDF.
I get the following LaTeX code (below) when I run an example in R (it renders ok in R, but I´d like to use TeXshop). However, when I paste this into a TeXshop window, I get the following error:
./Untitled.tex:2: LaTeX Error: Environment table undefined
I´m sure there is something very basic I´m missing here.
% latex.default(cstats, title = title, caption = caption, rowlabel = rowlabel,
% col.just = col.just, numeric.dollar = FALSE, insert.bottom = legend,
% rowname = lab, dcolumn = dcolumn, extracolheads = extracolheads,
% extracolsize = Nsize, ...)
%
\begin{table}[!tbp]
\caption{Descriptive Statistics by treatment\label{f}}
\begin{center}
\begin{tabular}{lccc}\hline\hline
\multicolumn{1}{l}{}&\multicolumn{1}{c}{Drug}&\multicolumn{1}{c}{Placebo}&\multicolumn{1}{c}{Test Statistic}\tabularnewline
&\multicolumn{1}{c}{{\scriptsize $N=263$}}&\multicolumn{1}{c}{{\scriptsize $N=237$}}&\tabularnewline
\hline
age&{\scriptsize 46.5~}{49.9 }{\scriptsize 53.2} &{\scriptsize 46.7~}{50.0 }{\scriptsize 53.4} &$ F_{1,498}=0.1 ,~ P=0.754 ^{1} $\tabularnewline
sex~:~m&47\%~{\scriptsize~(123)}&44\%~{\scriptsize~(104)}&$ \chi^{2}_{1}=0.42 ,~ P=0.517 ^{2} $\tabularnewline
Primary~Symptoms~:~Depressed&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Headache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Hangnail&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Muscle~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Stomach~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
\hline
\end{tabular}
\end{center}
\noindent
{\scriptsize $a$\ }{$b$\ }{\scriptsize $c$\ } represent the lower quartile $a$,
the median $b$, and the upper quartile $c$\ for continuous variables.\\
Numbers after percents are frequencies.\\\indent Tests used:\\
\textsuperscript{\normalfont 1}Wilcoxon test; \textsuperscript{\normalfont 2}Pearson test
\end{table}
You need some boilerplate around this to set up the document -- the LaTeXTemplate in TexShop should do.
Your \begin{table} is commented out with a preceding %
There are some missing backslashes in the legend text -- possibly these are just cut & paste artefacts?
This thrown-together version works for me, though you may need to tweak it for your purposes:
\documentclass[11pt]{article}
\begin{document}
\begin{table}[!tbp]
\caption{Descriptive Statistics by treatment\label{f}}
\begin{center}
\begin{tabular}{lccc}
\hline
\hline
\multicolumn{1}{l}{}&\multicolumn{1}{c}{Drug}&\multicolumn{1}{c}{Placebo}&\multicolumn{1}{c}{Test Statistic}
\tabularnewline
&\multicolumn{1}{c}{{\scriptsize $N=263$}}&\multicolumn{1}{c}{{\scriptsize $N=237$}}&
\tabularnewline
\hline
age&{\scriptsize 46.5~}{49.9 }{\scriptsize 53.2} &{\scriptsize 46.7~}{50.0 }{\scriptsize 53.4} &$ F_{1,498}=0.1 ,~ P=0.754 ^{1}$
\tabularnewline
sex~:~m&47\%~{\scriptsize~(123)}&44\%~{\scriptsize~(104)}&$ \chi^{2}_{1}=0.42 ,~ P=0.517 ^{2} $
\tabularnewline
Primary~Symptoms~:~Depressed&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Headache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Hangnail&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Muscle~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Stomach~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
\hline
\end{tabular}
\end{center}
\noindent {\scriptsize $a$\ }{$b$\ }{\scriptsize $c$\ } represent the lower quartile $a$, the median $b$, and the upper quartile $c$ for continuous variables.\\
Numbers after percents are frequencies.\\
\indent Tests used:\\
\textsuperscript{\normalfont 1}Wilcoxon test;
\textsuperscript{\normalfont 2}Pearson test
\end{table}
\end{document}
If you use the package stargazer (available on CRAN), you can use the argument out="filename.tex" to output the LaTeX code directly into a Tex document. That document should then be easy to compile.
It sounds like you may not have a document class defined, or you are not using a document class that defines the table environment.

Iteration in LaTeX

I would like to use some iteration control flow to simplify the following LaTeX code.
\begin{sidewaystable}
\caption{A glance of images}
\centering
\begin{tabular}{| c ||c| c| c |c| c|| c |c| c|c|c| }
\hline
\backslashbox{Theme}{Class} &\multicolumn{5}{|c|}{Class 0} & \multicolumn{5}{|c|}{Class 1} \\
\hline
\hline
1 &
\includegraphics[scale=2]{../../results/1/0_1.eps}
&\includegraphics[scale=2]{../../results/1/0_2.eps}
&\includegraphics[scale=2]{../../results/1/0_3.eps}
&\includegraphics[scale=2]{../../results/1/0_4.eps}
&\includegraphics[scale=2]{../../results/1/0_5.eps}
&\includegraphics[scale=2]{../../results/1/1_1.eps}
&\includegraphics[scale=2]{../../results/1/1_2.eps}
&\includegraphics[scale=2]{../../results/1/1_3.eps}
&\includegraphics[scale=2]{../../results/1/1_4.eps}
&\includegraphics[scale=2]{../../results/1/1_5.eps} \\
\hline
... % similarly for 2, 3, ..., 22
\hline
23 &
\includegraphics[scale=2]{../../results/23/0_1.eps}
&\includegraphics[scale=2]{../../results/23/0_2.eps}
&\includegraphics[scale=2]{../../results/23/0_3.eps}
&\includegraphics[scale=2]{../../results/23/0_4.eps}
&\includegraphics[scale=2]{../../results/23/0_5.eps}
&\includegraphics[scale=2]{../../results/23/1_1.eps}
&\includegraphics[scale=2]{../../results/23/1_2.eps}
&\includegraphics[scale=2]{../../results/23/1_3.eps}
&\includegraphics[scale=2]{../../results/23/1_4.eps}
&\includegraphics[scale=2]{../../results/23/1_5.eps} \\
\hline
\end{tabular}
\end{sidewaystable}
I learn that the forloop package provides the for loop. But I am not sure how to apply it to my case? Or other methods not by forloop?
If I also want to simply another similar case, where the only difference is that the directory does not run from 1, 2, to 23, but in some arbitrary order such as 3, 2, 6, 9,..., or even a list of strings such as dira, dirc, dird, dirb,.... How do I make the LaTeX code into loops then?
You may use pgffor package, a tool provided by pgf. The basic syntax is:
\foreach \n in {0,...,22}{do something}
Notably, this for loop is not restricted to integers, for example:
\foreach \n in {apples,burgers,cake}{Let's eat \n.\par}
Something like this will take care of the body of your tabular:
\newcounter{themenumber}
\newcounter{classnumber}
\newcounter{imagenumber}
\forloop{themenumber}{1}{\value{themenumber} < 24}{
% \hline <-- Error here
\arabic{themenumber}
\forloop{classnumber}{0}{\value{classnumber} < 2}{
\forloop{imagenumber}{1}{\value{imagenumber} < 6}{
& \includegraphics[scale=2]{
../../results/\arabic{themenumber}/\arabic{classnumber}_\arabic{imagenumber}.eps
}
}
}
\\
\hline
}
I had to comment out the first \hline because it gave me an error:
You can't use `\hrule' here except with leaders.
I'm not sure what that means; if you really cannot live without the double line, I can look into it more.
Also note that you have to use <; for example, <= 24 will not work.
As to your update: I would simply declare a command that takes the argument that you're looping over. Something like this:
\newcommand\fordir[1]{do something complex involving directory named #1}
\fordir{dira}
\fordir{dirb}
\fordir{dirc}
\dots

Resources