[Tex/LaTex] Multirow table with variable number of rows

multirowtablesvertical alignment

I'd like to format a table in which first column has a single line of text, centered vertically across a variable number of rows. Currently, I am using a IfEqCase and adding an entry in the first column only if some condition is met. This works as long as I have a fixed number of rows, and that number is odd (otherwise, the entry will not be vertically centered) :

\documentclass[11pt]{article}
\usepackage{multirow}
\usepackage{xstring}

\newcommand{\gridsize}[1]{\ensuremath{#1 \times #1}}

\newcommand{\addrowmpi}[4]{%
\IfEqCase{#1}{%
      {1} {&}  %
      {2} {\gridsize{#2} &}  %
      {4} {&}  %
}
#3 & #4 \%}

\begin{document}

\begin{table}[ht]
\caption{Multi-row table}
\begin{center}
\begin{tabular}{ccc}
    \hline
    \addrowmpi{1}{512}{462.7}{100} \\
    \addrowmpi{2}{512}{231.4}{50}\\
    \addrowmpi{4}{512}{115.7}{25}\\
    \hline
\end{tabular}
\end{center}
\label{tab:multicol}
\end{table}

\end{document}

The result looks like :

enter image description here

But I'd like to have a variable number of rows, formatted ideally with something like addrowmpi. The first column entry should be centered vertically across the rows.

Is there a way I can use the multirow environment with a variable number of rows?

Best Answer

By nesting tables I can do essentially what I had in mind. Here is the code I came up with (simplified somewhat from the above) :

\documentclass[11pt]{article}
\usepackage{array}

\newcolumntype{L}[1]{>{\raggedright\arraybackslash}m{#1}}
\newcolumntype{C}[1]{>{\centering\arraybackslash}m{#1}}
\newcolumntype{R}[1]{>{\raggedleft\arraybackslash}m{#1}}

\newenvironment{timingtable}
{\begin{tabular}{R{30pt}|R{30pt}|R{30pt}}}
{\end{tabular}}

\newcommand{\addrow}[3]{#1 & #2 &  #3 \%}

\setlength{\tabcolsep}{10pt}

\begin{document}

% Actual width of each column is 30 + 2*tabcolsep
\begin{table}[ht]
\caption{Multi-row table}
\begin{center}
\begin{tabular}{|C{20pt}|@{}p{150pt}@{}|}
    \hline
    512 &
    \begin{timingtable}
    \addrow{462.7}{222.0}{100} \\
    \addrow{231.4}{111.0}{50} \\
    \addrow{154.2}{74.0}{33} \\
    \addrow{115.7}{37.0}{25} \\
    \end{timingtable} \\
   \hline
\end{tabular}
\end{center}
\label{tab:multicol}
\end{table}

\end{document}

Multi-row column

The first column has width 20 + 2*tabcolsep = 40pt, expected. And each column in the nested table has width 30+2*tabcolsep = 50. The @{} in the outer tabular command suppresses the additional tabcolsep space that would be added around the nested table, making the first and last columns of the nested table too wide.

Related Question