[Tex/LaTex] Diagonal lines in table cell

tables

I need this table:

table

(each row and column should have the same height and length, last cell should be divided by diagonal line). I tried the following code:

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{array}
\usepackage{makecell}
\newcolumntype{x}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}p{#1}}
\begin{document}
\setlength{\extrarowheight}{0.1cm}
\begin{tabular}{|x{0.5cm}|x{0.5cm}|x{0.5cm}|x{0.5cm}|x{0.5cm}|}\hline
&&&&20\\ \hline
&&&&30\\ \hline
&&&&45\\ \hline
15&12&18&50&\diaghead(-3,2){\hskip \hsize}{$a_i$}{$b_j$}\\ \hline
\end{tabular}
\end{document}

but text in the last cell is displayed incorrectly and cells are not the same.

table - latex

How can I change that?

Best Answer

Exact solution with TikZ:

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{array}
\usepackage{makecell}
\newcolumntype{x}[1]{>{\centering\arraybackslash}p{#1}}

\usepackage{tikz}
\newcommand\diag[4]{%
  \multicolumn{1}{p{#2}|}{\hskip-\tabcolsep
  $\vcenter{\begin{tikzpicture}[baseline=0,anchor=south west,inner sep=#1]
  \path[use as bounding box] (0,0) rectangle (#2+2\tabcolsep,\baselineskip);
  \node[minimum width={#2+2\tabcolsep},minimum height=\baselineskip+\extrarowheight] (box) {};
  \draw (box.north west) -- (box.south east);
  \node[anchor=south west] at (box.south west) {#3};
  \node[anchor=north east] at (box.north east) {#4};
 \end{tikzpicture}}$\hskip-\tabcolsep}}

\begin{document}
\setlength{\extrarowheight}{0.1cm}
\begin{tabular}{|x{0.5cm}|x{0.5cm}|x{0.5cm}|x{0.5cm}|x{0.5cm}|}\hline
&&&&20\\ \hline
&&&&30\\ \hline
&&&&45\\ \hline
15&12&18&50&\diag{.1em}{.5cm}{$a_i$}{$b_j$}\\ \hline
\end{tabular}
\end{document}

enter image description here

Also it is a reimplementation of \diaghead.

Related Question