Matrix in Tikz with centered Numbers (especially negative numbers)

aligncentermatricestikz-pgf

I've got the following problem with negative numbers in my matrix:

\begin{tikzpicture}[>=latex]
\matrix (m) [matrix of math nodes,
left delimiter=(,right delimiter=),
inner ysep=0pt, column sep=0.8em, row sep = 0.65em,
nodes={inner sep=0.3em,text width=0.85em,align=center}
]
{
    1 & 2 & 1 &  0\\
    0 & -2 & 1 & 0\\
    0 & 0 & 0 & 0\\
};
\path ($(m-1-3.north east)+(0.3em,0)$) edge[thick] ($(m-3-3.south east -| m-1-3.north east)+(0.3em,0)$);
\end{tikzpicture} 

I tried anchor = center as well as align = center, but the negative number still looks awkward. Its not centered..

Which option am I missing? Ty for your help!

Best Answer

The issue here is not with the text alignment, what you did is correct on this side. The issue comes from the text width which is too small for -2 to fit in. Reduce you inner sep and use a larger text width:

matrix with centred figures

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{matrix,calc}

\begin{document}

    \begin{tikzpicture}[>=latex]
        \matrix (m) [matrix of math nodes,
        left delimiter=(,right delimiter=),
        inner ysep=0pt, column sep=0.8em, row sep = 0.65em,
        nodes={inner sep=0.1em,outer sep=0,text width=1.2em,align=center}
        ]
        {
            1 & 2 & 1 &  0\\
            0 & -2 & 1 & 0\\
            0 & 0 & 0 & 0\\
        };
        \path ($(m-1-3.north east)+(0.3em,0)$) edge[thick] ($(m-3-3.south east -| m-1-3.north east)+(0.3em,0)$);
    \end{tikzpicture}

\end{document}

You can also use inner ysep and inner xsep separately if you want to get a wider or a higher matrix.