Stage 3 · Mathematics 18 / 48 ≈ 29 min read

Matrices in LaTeX: pmatrix, bmatrix, array, Augmented Bars

Every matrix in LaTeX is the same grid wearing a different fence: which wrapper for which object, how the & and \\ grammar works, where an array column spec lets you draw rules, and how to keep dots, labels and tall cells honest.

    One grid, six fences

    There is exactly one matrix mechanism in amsmath, and the environments you type are thin coats of paint on it. Each of matrix, pmatrix, bmatrix, Bmatrix, vmatrix and Vmatrix opens the same alignment — an array whose preamble is a fixed list of c columns — and then bolts on a delimiter: nothing, round, square, curly, single bar, double bar. The mnemonic is in the name and the case: the leading letter is the fence, and capitals double it. Nothing else about them differs, so everything you learn about one transfers intact.

    Because the preamble is fixed before a single entry is read, the grammar of the body is short and absolutely rigid. An & steps to the next column, a \\ steps to the next row, and that is the entire instruction set: no options, no arguments, no per-row changes to alignment. The environments take no optional [c] or [t] either — a matrix box vertical-centres itself against whatever it sits beside, and if that is wrong, the fix is in the material around it rather than in the \begin line. The row count is free, the column count is not: the preamble amsmath generates is *\c@MaxMatrixCols c, and that counter is ten, so the eleventh & in a row is a hard stop rather than a warning, with the same message an array gives when you overshoot its declared column count.

    Each cell is processed in its own group, in maths mode and in text style, and all three halves of that sentence matter. Maths mode means spaces inside a cell are ignored and a run of letters is a product of variables, so any word needs \text{…} before it is a word at all. The group means a declaration made in one cell dies in that cell. And text style means the display conventions do not apply: fractions come out collapsed and operators keep their limits to the side, which is why a cell that looked right in a scratch pad prints small in the finished matrix — not a bug in the environment but the environment telling you the truth about where it sits.

    \begin{pmatrix} a & b \\ c & d \end{pmatrix}
    \begin{pmatrix} a & b \\ c & d \end{pmatrix}
    Only array itself predates amsmath: every *matrix name is undefined without \usepackage{amsmath}, and the failure is a message about the environment, not about the entries inside it.
    \begin{matrix} a & b \\ c & d \end{matrix} \qquad \begin{Bmatrix} a & b \\ c & d \end{Bmatrix} \qquad \begin{Vmatrix} a & b \\ c & d \end{Vmatrix}
    \begin{matrix} a & b \\ c & d \end{matrix} \qquad \begin{Bmatrix} a & b \\ c & d \end{Bmatrix} \qquad \begin{Vmatrix} a & b \\ c & d \end{Vmatrix}
    Matrices in LaTeX: pmatrix, bmatrix, array, Augmented Bars — One grid, six fences
    Rendered output — typeset from the source shown on this page.

    Which wrapper for which object

    The choice of fence carries meaning that a reader absorbs without noticing, and it is not interchangeable. pmatrix is the general-purpose array of numbers — a matrix named, displayed, and talked about. bmatrix tends to be reserved for the objects that do something: coefficient matrices, change-of-basis and transformation matrices, the matrix of a linear map. vmatrix is a determinant — a scalar produced by a grid rather than the grid itself — and the notation around it, when to write \det rather than bars and how signs behave under the operations you are about to list, belongs to the determinants reference and not to this page. Vmatrix is the least settled of the six: double bars elsewhere in maths mean norm and inner product, and where the form is used at all it is usually for the norm of the operator a grid represents, so its reading depends heavily on what stands around it. Bmatrix is rare, and mostly means "a set written as a grid".

    Two rules cover almost every real decision. The first is consistency: pick the convention once per document and hold it, because a paper that writes pmatrix in section 2 and bmatrix for the same species of object in section 5 reads as three papers stapled together, and a copy editor's eye catches that long before it catches a bad line break. The second is that the fence is part of the environment that owns it: if you want a matrix in square brackets, type bmatrix. Do not type matrix and add your own brackets by hand, because your typed [ is an ordinary maths atom with no idea that a tall box is about to appear next to it, while bmatrix's is a delimiter built for that box — sized with it, spaced with it, and centred on it.

    What about the bare matrix, the wrapper with no fence? It earns its keep in two places. One is as an entry of a larger grid: a block matrix whose blocks are themselves matrices needs the inner grids to arrive without opinions about delimiters. The other is when the delimiter belongs to something bigger than the matrix — a bracket that also encloses a following factor, an evaluation bar, a case distinction — where the fence has to be supplied from outside and sized against the whole construction, which is the brackets-and-sizing lesson's question rather than this one's. Choosing matrix is the moment the fence becomes your problem.

    \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}
    \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}
    If two symbols are the same kind of object, they get the same wrapper — including in a display you are quoting from someone else's paper, where silently changing the fence is a notation edit you did not intend to make.
    \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix} \begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} x^{\prime} \\ y^{\prime} \end{pmatrix}
    \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix} \begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} x^{\prime} \\ y^{\prime} \end{pmatrix}

    Dots that keep the grid honest

    A large matrix is a small matrix plus an agreement about what continues. The agreement is written with dots, and there are four that matter, each one shaped for a direction. \cdots sits at the maths centre and continues a row; \ldots sits on the baseline and continues a list separated by commas; \vdots continues a column; \ddots continues the diagonal, and is the only one whose alignment is not free — it has to land where the diagonal actually goes, which means the columns around it need to be roughly regular or the eye reads a break in the pattern. The rule generating the rest is short: entries at operator height want centred dots, entries at punctuation height want baseline ones, and a \cdots standing in a column reads as a subtraction that never arrives.

    The structural rule is stricter than the typographic one, and it is the one that keeps a matrix from falling apart: a dot is a cell. \vdots does not create a row and \ddots does not create columns — they occupy a cell and imply that the grid continues in the direction they are shaped for, while every row still has to carry the same number of & characters as every other row, exactly as it would without them. Hence the canonical three-by-three skeleton — three rows of three cells, dots in the corners and in the middle — and hence the answer to "how do I show a hundred by hundred matrix", which is not to draw it: three named entries, one diagonal, and a sentence saying what fills the rest is honest, smaller on the page, and impossible to misread.

    amsmath's \dots saves you from choosing, and knowing that it exists prevents a whole class of second-guessing: it inspects what follows and picks the centred or baseline form accordingly, so a_1 + \dots + a_n and a_1, a_2, \dots, a_n both come out right from the same four characters. The explicit family behind it — \dotsc, \dotsb, \dotsm — lets you overrule the automatic pick. What is never right is three typed periods: ... is three baseline dots with punctuation spacing, wrong for every direction a grid runs and invisible in the log, which makes it the commonest way a matrix looks amateurish with nothing actually wrong in it. The one direction core LaTeX has no glyph for is the rising diagonal; that needs a package, and the cheaper answer is to re-write the matrix so the pattern runs the other way.

    \begin{pmatrix} 1 & \cdots & n \\ \vdots & \ddots & \vdots \\ n & \cdots & 1 \end{pmatrix}
    \begin{pmatrix} 1 & \cdots & n \\ \vdots & \ddots & \vdots \\ n & \cdots & 1 \end{pmatrix}
    Put the dots in the cell where the missing entries would be and count the & on that row against its neighbours — a row that is short by one cell still compiles, it just moves everything after the gap one column to the left.
    \begin{pmatrix} 1 & 1 & \cdots & 1 \\ x_{1} & x_{2} & \cdots & x_{n} \\ x_{1}^{2} & x_{2}^{2} & \ddots & \vdots \\ \vdots & \vdots & \ddots & x_{n}^{n-1} \end{pmatrix}
    \begin{pmatrix} 1 & 1 & \cdots & 1 \\ x_{1} & x_{2} & \cdots & x_{n} \\ x_{1}^{2} & x_{2}^{2} & \ddots & \vdots \\ \vdots & \vdots & \ddots & x_{n}^{n-1} \end{pmatrix}

    array: the layer under everything, and where the rules come from

    The moment you want anything the wrappers cannot do — a column aligned left or right instead of centred, a vertical rule, a horizontal rule, a header row, text that occupies a declared width — you leave the *matrix family and use array, which is not an alternative to them but the thing they are made of. Its one mandatory argument is a column specification, one token per column, and the vocabulary is small: l, c, r for the three alignments, | to draw a rule between columns, @{material} to replace the inter-column glue with something of your own, *n{spec} to repeat a chunk, and — with the array package loaded — ! for a rule that costs no column, and p{width} for the wrapping column maths grids do not otherwise provide. The count is enforced: a row with more cells than the preamble declares stops with ! Extra alignment tab has been changed to \cr., which is annoying and also the reason array catches ragged grids that a pmatrix swallows without complaint.

    The classic use, and the one that draws people to this page, is the augmented matrix: \begin{array}{cc|c} declares two coefficient columns, a rule, and the constants column, and the bar is preamble syntax rather than content, which means re-partitioning the grid is a one-character edit. {c|cc} moves it to split one coefficient from two; {cc|cc} handles two right-hand sides at once. The horizontal counterpart is \hline, placed as its own row between two \\, and it is the tool for the header row that separates labels from entries. One asymmetry to know before you need it: array is the only member of the family that arrives with no delimiters at all, so an augmented matrix needs its brackets supplied from outside, and how tall to make them is a question the brackets-and-sizing lesson answers; what matters here is only that the fence and the rule are independent objects, and the rule is not a delimiter.

    Alignment inside a grid follows the column, not the content. Centred columns are right for symbolic entries — a_{ij}, \lambda, single letters — because the eye wants the vertical rhythm and there is no run of digits to compare. Numeric columns want r, so magnitudes line up on the right, and where you specifically need a decimal column, the trick is a pair of columns with the separator as material rather than content: {r@{.}l} puts one digit group on each side of a literal period, and the row is then 12&345 rather than 12.345. The alternative, padding the short numbers with \phantom{0}, keeps the source readable and is usually the better trade for a table with two or three rows. Numbers with units and errors are a table rather than a matrix, and siunitx's S column is the right tool there — it just cannot live inside a maths display, which is why the @{.} trick survives.

    \begin{array}{cc|c} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}
    \begin{array}{cc|c} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}
    Add @{} at both ends of the preamble and the brackets stop floating a full \arraycolsep away from the entries they enclose; the two spaces you delete are the ones LaTeX adds because it assumes another column follows.
    \begin{array}{rr|r} a & b & \text{rhs} \\ \hline 1 & -2 & 3 \\ 45 & 5 & -6 \end{array}
    \begin{array}{rr|r} a & b & \text{rhs} \\ \hline 1 & -2 & 3 \\ 45 & 5 & -6 \end{array}
    % Preamble: \usepackage{amsmath}
    \[
      A \mathbf{x} = \mathbf{b}, \qquad
      A = \begin{pmatrix}
            2 & -1 &  0 \
           -1 &  2 & -1 \
            0 & -1 &  2
          \end{pmatrix}, \quad
      \mathbf{x} = \begin{pmatrix} x_1 \ x_2 \ x_3 \end{pmatrix}
    \]

    The outside edge: fences, subscripts, and juxtaposition

    A finished matrix is one box, and the interesting questions start where its fence ends. Indices belong on the grid rather than inside it — \begin{pmatrix} … \end{pmatrix}_{ij} says the object as a whole carries the subscript, and hangs it off the closing delimiter — while a_{ij} inside the cells says each entry is separately indexed, and that is a different claim about a different object. Two details make the subscript read as attached instead of leaning: the delimiter is an ordinary closing atom to TeX, so the subscript positions itself by its own rules and can look detached on a wide matrix, which is what the negative space in }_{\!ij} is for; and a subscript that is really an adjective ("the matrix C of size ij") belongs on the name in the sentence, not on the display.

    Two grids standing side by side are a product, and a product written without a sign is only legible if the reader can see that there are two things. Adjacent fences are the weak form of that signal: the boxes touch, the eye integrates them into one wider grid, and the multiplication is implied rather than shown. There are three honest ways out, in ascending order of preference for anything beyond a two-by-two: name the factors and write A\,\mathbf{x} so the objects have handles the prose can reuse; write the product with the grids and let a thin space do the separating; or, when the factors are long and the result matters more than the working, break the line and put one factor on each side of the =. The sizes and what each one costs are the spacing lesson's subject; the container-level decision is simply that a juxtaposition of boxes needs air, and adding it by typing spaces will do nothing at all because maths mode ignores them.

    Punctuation goes outside the fence, in the order your prose reads it: \end{pmatrix}. and \end{pmatrix}; are both fine, and a full stop hidden in the last cell is not. Punctuation is otherwise just another argument to the general rule that a matrix is an ordinary maths atom: it sits inside an aligned row without ceremony, it can be one side of an = that other rows continue, and it can stand beside \text{…} in a derivation. The restrictions are equally plain. A grid cannot straddle a line break, so a matrix wide enough to overflow the text block is a layout problem with a layout answer — block-partition it, transpose it, or split it across two displays — and none of those is a syntax fix. A \left/\right pair must open and close in the same box, so it goes around a whole matrix, never half in and half out. And because a grid is a box and not a structure, it carries no equation number of its own: the number belongs to whatever display it is the body of.

    C_{ij} = \begin{pmatrix} a & b \\ c & d \end{pmatrix}_{\!ij} \qquad \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}
    C_{ij} = \begin{pmatrix} a & b \\ c & d \end{pmatrix}_{\!ij} \qquad \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}
    To align the cells of two matrices that sit in consecutive rows of a derivation, you do not have two matrices — you have one array with a wider preamble, and the alignment you wanted comes free with it.

    Tall cells, crowded grids, and the ten-column wall

    Cells are text style, and text style is where fractions go to look wrong. \frac{\partial u}{\partial t} inside a pmatrix prints with the numerator and denominator crushed to script size, and the fix is per cell rather than per environment: \dfrac for a fraction that should keep display size, \limits to force limits above and below an operator, or \displaystyle at the head of a cell when the cell contains something you cannot rewrite. Reaching for a bigger delimiter to compensate is the wrong lever — the delimiter is answering a height question you have not actually solved, and the cell is still cramped.

    When a cell genuinely needs more than one line — a pair of simultaneous expressions, a piecewise entry, a vector written vertically in a position that wants a scalar — the nested box is the tool, and there are two of them worth knowing. subarray is the compact one: \begin{subarray}{c} x_1 \\ x_2 \end{subarray} stacks material and takes an alignment letter, and because it sizes to its content rather than to the grid, it is the right choice inside a cell. aligned is the other, useful when the stacked lines have their own anchor. What is not a tool here is a row of the outer grid: & cannot create a second line inside one cell, and a blank line is a paragraph end in maths, which is how you arrive at ! Missing $ inserted. with every dollar sign present. Vertical air around a row comes from \\[6pt] on that row, which is local, honest, and does not disturb the row count the way an empty row would — and the block-level lever is \arraystretch, which multiplies the strut every row carries and is the only clean way to loosen a whole matrix at once. Note that the \jot length people reach for after working in align does nothing here: it belongs to the equation structures, not to grids.

    Density has one length and one counter that will eventually bite. The length is \arraycolsep, the padding LaTeX adds on each side of a cell — which means a neighbouring pair of columns gets twice it, and a dense grid of multi-character entries starts to push its own brackets away from its content. The cure is local: a group containing \setlength{\arraycolsep}{2pt} in front of the display, or @{} at the outer ends if the problem is only the edges, and never spaces typed into cells, because maths mode will discard them along with everything else it does not recognise as content. The counter is MaxMatrixCols, ten by default, and it is the reason an eleven-column grid stops compiling at all; \setcounter{MaxMatrixCols}{20} inside a group lifts the ceiling for that one matrix, but a grid that needs eleven declared columns in a text-width display is telling you something about your layout — the block form, with named sub-matrices as entries, is almost always both smaller on the page and easier to read.

    \begin{pmatrix} \dfrac{\partial u}{\partial t} \\[6pt] \dfrac{\partial v}{\partial t} \end{pmatrix} \qquad \begin{pmatrix} \begin{subarray}{c} x_{1} \\ x_{2} \end{subarray} & 0 \\ 0 & \begin{subarray}{c} y_{1} \\ y_{2} \end{subarray} \end{pmatrix}
    \begin{pmatrix} \dfrac{\partial u}{\partial t} \\[6pt] \dfrac{\partial v}{\partial t} \end{pmatrix} \qquad \begin{pmatrix} \begin{subarray}{c} x_{1} \\ x_{2} \end{subarray} & 0 \\ 0 & \begin{subarray}{c} y_{1} \\ y_{2} \end{subarray} \end{pmatrix}
    Wrap a local change in a group — {\setlength{\arraycolsep}{2pt} … \end{pmatrix}} — and the next matrix in the document is unchanged; changing these lengths at the top level is how a paper ends up with two different matrices that are silently not the same size.
    % ============================================================
    % Structured grids: the augmented matrix, its rules, and what
    % happens when a grid outgrows the preamble amsmath gives it.
    % Needs pdflatex + amsmath; the array package is loaded for the
    % ! separator and \extrarowheight.
    % ============================================================
    \documentclass[11pt,a4paper]{article}
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage{array}
    
    \begin{document}
    
    \section{One rule, three partitions}
    The bar is part of the preamble, so moving it is a one-character edit.
    \[
      \left[\begin{array}{cc|c} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right]
      \qquad
      \left[\begin{array}{c|cc} 1 & 2 & 3 \\ \hline 4 & 5 & 6 \end{array}\right]
      \qquad
      \left[\begin{array}{cc|cc} 1 & 0 & 3 & 0 \\ 0 & 1 & 0 & 5 \end{array}\right]
    \]
    The last one is two right-hand sides: one column of the preamble per
    constant, and one bar between the coefficients and them.
    
    \section{Trimming the edges}
    Inter-column space is \texttt{\textbackslash arraycolsep} on BOTH sides of a
    neighbouring pair, so the fence floats away from the entries it encloses.
    \texttt{@\{\}} at the outer ends of the preamble deletes exactly that glue,
    and nothing else:
    \[
      \left[\begin{array}{cc|c} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right]
      \qquad
      \left[\begin{array}{@{}cc|c@{}} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right]
    \]
    
    \section{Row reduction, which is two grids and one label}
    A grid is a box, so the arrow between two of them has to be part of the
    same box. Either put both on one line, or stack them in an outer
    \texttt{array}; there is no way to break a grid itself.
    \[
      \left[\begin{array}{cc|c} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right]
      \ \xrightarrow{\;R_2 \leftarrow R_2 - 4R_1\;}\
      \left[\begin{array}{cc|c} 1 & 2 & 3 \\ 0 & -3 & -6 \end{array}\right]
    \]
    
    \section{A dense grid, locally}
    Reducing the padding for one matrix without touching the rest of the
    document: a group, because the length is a declaration and it ends with it.
    \[
      \left\{\,\begin{array}{@{}ccc@{}}
        a_{11} & a_{12} & a_{13} \\
        a_{21} & a_{22} & a_{23}
      \end{array}\,\right\}
      \qquad
      \begingroup
      \setlength{\arraycolsep}{2pt}
      \renewcommand{\arraystretch}{1.2}
      \begin{pmatrix} 1 & 0 & 0 & -2 \\ 0 & 1 & 0 & 3 \\ 0 & 0 & 1 & 1 \end{pmatrix}
      \endgroup
    \]
    
    \section{The wall: more columns than the preamble holds}
    amsmath builds every matrix environment as an \texttt{array} whose preamble
    is ten \texttt{c} columns (\texttt{MaxMatrixCols}, and its default is 10).
    A row with an eleventh cell steps past the end of that preamble and TeX
    stops:
    \begin{quote}\ttfamily
    ! Extra alignment tab has been changed to \string\cr.
    \end{quote}
    The cure is local, and the counter is a counter, not a length:
    \[
      \begingroup
      \setcounter{MaxMatrixCols}{20}
      \begin{pmatrix}
        1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
        0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 2
      \end{pmatrix}
      \endgroup
    \]
    The honest cure for an eleven-column matrix in a paragraph-sized display is
    a block form or a wider page, not a bigger counter.
    
    \end{document}

    Labels outside the grid: bordermatrix, kbordermatrix, blkarray, nicematrix

    Ask for "a matrix with row and column names" and two quite different jobs appear, and the first is already solved: labels inside cells work in every container on this page, with \text{…} doing the ordinary work of turning a run of italic variables into a word. The job that needs a separate tool is labels outside the fence — a header row and a header column that the brackets do not enclose — and no *matrix environment can do it, because their geometry is fixed at fence-grid-fence and there is no slot for material the delimiters exclude.

    Four tools claim the job, and they differ by grammar more than by appearance. \bordermatrix is plain TeX's, which tells you most of what you need to know: its rows end with \cr rather than \\, so you are learning a second dialect beside the one on the rest of this page; it draws no delimiters, gives the header cells no styling control, and it is not part of the LaTeX kernel, so on a lean format the name may simply not exist. kbordermatrix is a LaTeX-side re-implementation of the same idea — same \cr grammar, now with the brackets and a couple of font hooks — and it is the smallest upgrade if all you wanted was the plain shape with square ends. blkarray is the one that stops being a special case: an outer blockarray declares one column per label-plus-entry pair, and an inner block whose preamble marks the bordered columns with brackets, all in ordinary & and \\ grammar, which is also the only one of the three that handles a partial rule cleanly. And nicematrix is the modern answer, with the header cells as options on the \begin line (first-row and first-col; older versions called them top-header and left-header) and the fence coming from the environment name, so for the first time the labels and the brackets are properties of one object.

    Then the cost, which is the part people discover late. All of the last two — and bordermatrix before them — require a real LaTeX run with the package present: nicematrix in particular pulls in TikZ, wants a reasonably recent distribution, and needs the extra compile pass for its rules and block shading to settle. None of them exists in a browser-side maths renderer, so a formula that uses them on a web page arrives as raw source text to the reader, and if your document is destined for a proceedings template that runs one pass, "it worked on my machine" is the whole of the story. The portable construction, which renders everywhere array does and needs no package, is the hand-built one: make the header row and label column ordinary cells of a wider array, draw the separation with | and \hline, and wrap the whole thing in your own delimiters. It is two lines more source and it never fails to appear.

    \begin{array}{c|ccc} & c_{1} & c_{2} & c_{3} \\ \hline r_{1} & 1 & 0 & 0 \\ r_{2} & 0 & 1 & 0 \end{array}
    \begin{array}{c|ccc} & c_{1} & c_{2} & c_{3} \\ \hline r_{1} & 1 & 0 & 0 \\ r_{2} & 0 & 1 & 0 \end{array}
    Decide by destination, not by taste: if the same source must serve a paper and a web page, use the hand-built array version and keep nicematrix for the document where the labels belong to the figure rather than to the maths.
    % ============================================================
    % Four ways to put row and column labels OUTSIDE a grid, in
    % ascending order of modernity. None of them exists in a
    % browser-side renderer: see the lesson for the portable form.
    % ============================================================
    \documentclass[11pt,a4paper]{article}
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage{blkarray}       % blockarray / block, with rules
    \usepackage{kbordermatrix}  % a LaTeX-side version of plain TeX's \bordermatrix
    \usepackage{nicematrix}     % the NiceMatrix family; pulls in TikZ, needs a recent LaTeX
    
    \begin{document}
    
    \section{Plain TeX's macro}
    Rows end with \verb|\cr|, not with \verb|\\|, and the delimiters are not
    there: \verb|\bordermatrix| draws a grid plus two header cells and nothing
    else. It comes from plain TeX rather than the LaTeX kernel, so on a lean
    format the name may simply be undefined.
    \[
      M = \bordermatrix{ & c_1 & c_2 \cr
                        r_1 & 1 & 0 \cr
                        r_2 & 0 & 1 \cr}
    \]
    
    \section{Same shape, with brackets}
    \verb|\kbordermatrix| keeps the \verb|\cr| grammar and adds the brackets
    plain TeX leaves off, plus a couple of font hooks.
    \[
      M = \kbordermatrix{ & c_1 & c_2 \cr
                         r_1 & 1 & 0 \cr
                         r_2 & 0 & 1 \cr}
    \]
    
    \section{blkarray: LaTeX grammar, and you say where the rules go}
    An outer \verb|blockarray| declares one column per label-plus-entry pair;
    the inner \verb|block| preamble marks the columns that get borders with
    square brackets. This is the one that handles partial rules cleanly.
    \[
      \begin{blockarray}{ccc}
              & c_1 & c_2 \\
        \begin{block}{c[cc]}
          r_1 & 1  & 0 \\
          r_2 & 0  & 1 \\
        \end{block}
      \end{blockarray}
    \]
    
    \section{nicematrix: headers as an option}
    Current nicematrix takes the header cells as options on the
    \verb|\begin| line (older versions spelled them
    \verb|top-header| / \verb|left-header|); the fence comes from the
    environment name, so the labels and the brackets are finally the same
    object. Rules and block shading need a second compile pass.
    \[
      \begin{pNiceMatrix}[first-row,first-col]
              & c_1 & c_2 \\
        r_1   & 1   & 0   \\
        r_2   & 0   & 1
      \end{pNiceMatrix}
      \qquad
      \begin{NiceMatrix}[bordered]
        1 & 0 \\ 0 & 1
      \end{NiceMatrix}
    \]
    
    \section{The portable answer, for comparison}
    No package, no extra grammar: the labels are ordinary cells, the rules are
    a \texttt{|} and an \texttt{\textbackslash hline}, the brackets are yours.
    \[
      \left[\begin{array}{c|cc} & c_1 & c_2 \\ \hline r_1 & 1 & 0 \\ r_2 & 0 & 1 \end{array}\right]
    \]
    
    \end{document}

    A grid in a sentence, and where this page stops

    A display-size matrix inside running text forces the line taller than the paragraph's rhythm, and the line gap around it goes wrong in a way you can see but have trouble naming. amsmath's answer at the container level is smallmatrix: same grammar and same cell rules, but its entries are set at script size with a reduced row gap, so a two-by-two occupies barely more than a line. It has no fence of its own, so the house style is a pair of fixed-size delimiters around it — \bigl( \begin{smallmatrix} … \end{smallmatrix} \bigr) — and using \left/\right there is precisely the wrong move, since auto-sizing in a line of text is how you get one stretched line in the middle of an otherwise even paragraph. The nicematrix family ships the same idea with the fence built in, as psmallmatrix and its siblings. What the size does to the baseline and the surrounding spacing is a question the spacing lesson owns; the decision this page cares about is the earlier one, namely that a matrix in prose is a choice with a budget attached, and the budget is a two-by-two. If you find yourself writing three rows inside a sentence, the sentence wants "the matrix $A$ above" and the grid wants a display of its own.

    Three neighbouring topics look like matrix topics and are not, and this page deliberately stops at their borders. A determinant is a scalar produced by a grid, its bars are a different delimiter with different conventions, and the sign behaviour under row operations, the cofactor expansions and the transposed forms are the determinants reference's material — the only thing this lesson adds is the notation rule that vmatrix means determinant and bmatrix never does. A column of numbers is a vector, shares the grid machinery, and is settled by a typography question that belongs to the vectors and bold-and-italic references: arrow accent or bold typeface, and never italicised letter-by-letter when the name has more than one character in it. A system of equations is an alignment question wearing a matrix costume: a brace grouping several lines is cases or an array{l} inside a left delimiter, and when a system refuses to line up the cause is almost always an uneven & count between rows rather than anything to do with brackets — the row grammar and the numbered variants are the multi-line equations lesson.

    And arithmetic is out of scope by design, which is worth stating because it is the most-searched thing this page cannot answer. LaTeX typesets matrices; it does not invert them, does not multiply them for you, and does not know that the entries on the second line should depend on the first. For computed output the options are a system that drives a computer-algebra back end, such as SageTeX, or doing the algebra somewhere else and typesetting the result — and if the result reached you as a picture, from a lecture slide, an exam paper or a friend's phone, then the bottleneck is not the container at all: it is getting the grid into editable source in the first place. The formula converter on this site returns exactly the pmatrix text this page teaches, and the two things worth checking after any conversion are the ones that break silently — a \vdots that came back as a stray period, and a row that lost its & and is now a longer row than its neighbours.

    T = \bigl(\begin{smallmatrix} 1 & 0 \\ 0 & -1 \end{smallmatrix}\bigr) \qquad \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}
    T = \bigl(\begin{smallmatrix} 1 & 0 \\ 0 & -1 \end{smallmatrix}\bigr) \qquad \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}
    Before reaching for smallmatrix, ask whether the entries are the point at all: naming the matrix in the sentence and letting the grid have a display of its own two lines later keeps the paragraph even.
    \begin{bmatrix} A & 0 \\ 0 & B \end{bmatrix} \begin{pmatrix} \mathbf{x} \\ \mathbf{y} \end{pmatrix} = \begin{pmatrix} \mathbf{p} \\ \mathbf{q} \end{pmatrix}
    \begin{bmatrix} A & 0 \\ 0 & B \end{bmatrix} \begin{pmatrix} \mathbf{x} \\ \mathbf{y} \end{pmatrix} = \begin{pmatrix} \mathbf{p} \\ \mathbf{q} \end{pmatrix}
    % ============================================================
    % Matrices inside running text, and the small mechanics that
    % decide whether a paragraph survives them.
    % ============================================================
    \documentclass[11pt,a4paper]{article}
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    
    \begin{document}
    
    % smallmatrix: entries at scriptstyle, tighter row gap, NO fence of its
    % own. Fixed-size delimiters, because \left...\right in a line of text
    % will stretch the line height.
    Let $B=\bigl(\begin{smallmatrix} 1 & 2 \\ 3 & 4 \end{smallmatrix}\bigr)$,
    so that $\det B = -2$ while the display-size copy
    \[
      B = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}
    \]
    says the same thing at the price of a display of its own.
    
    % A grid cannot straddle a line break. In text, that means the fence of a
    % matrix is a break opportunity you do NOT want: keep the whole thing in
    % one unbreakable box by leaving it inside a single pair of $...$.
    
    % Words in a cell are otherwise read as a product of variables.
    \[
      \begin{array}{c|cc}
        & \text{in} & \text{out} \\ \hline
        \text{stage 1} & 0.4 & 0.6 \\
        \text{stage 2} & 0.1 & 0.9
      \end{array}
    \]
    
    % Two lines inside one cell: a nested box, never a blank line and never a
    % row of the outer grid.
    \[
      \begin{pmatrix}
        \begin{aligned} x &= 1 \\ y &= 2 \end{aligned} & 0 \\
        0 & \begin{subarray}{c} a+b \\ c+d \end{subarray}
      \end{pmatrix}
    \]
    
    % Row-specific air, and the fact that \jot does nothing here.
    \[
      \begin{pmatrix} 1 & 0 \\[8pt] 0 & 1 \end{pmatrix}
      \qquad
      {\renewcommand{\arraystretch}{1.6}
       \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}}
    \]
    
    \end{document}

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    \begin{pmatrix} a & b \\ c & d \end{pmatrix}
    \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}
    \begin{pmatrix} 1 & \cdots & n \\ \vdots & \ddots & \vdots \\ n & \cdots & 1 \end{pmatrix}
    C_{ij} = \begin{pmatrix} a & b \\ c & d \end{pmatrix}_{\!ij} \qquad \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}
    \documentclass[11pt,a4paper]{article}

    Common mistakes

    • ! LaTeX Error: Environment pmatrix undefined. — the *matrix names are amsmath's, not the kernel's, so a document that never loads \usepackage{amsmath} has no matrix environments at all. The same source with array instead compiles, which is what makes the message look mysterious: only array predates the package.
    • Mixing up the two separators: \\ ends a row and & steps to the next column, so swapping them gives either one absurdly long row or ! Extra alignment tab has been changed to \cr. — the same message as an eleventh column in a default matrix, since the preamble amsmath builds is ten c columns wide and \setcounter{MaxMatrixCols}{20} in a group is the only syntax-level cure.
    • A trailing \\ on the last row. No error is produced, which is the problem: the environment obediently starts an empty row, the grid grows by one line-height, the delimiter grows with it, and the matrix sits low in its brackets until you find the two characters that caused it.
    • Typing ... for "and so on". Those are three baseline dots with punctuation spacing, wrong for a row, wrong for a column, wrong for the diagonal, and invisible in the log — \cdots, \vdots and \ddots are shaped for the three directions, and amsmath's \dots picks between the horizontal forms by looking at what follows.
    • Wrapping a bare matrix in hand-typed brackets, [\begin{matrix}…\end{matrix}]. It renders, and the spacing is wrong at both ends because your [ is an ordinary maths atom with no knowledge of the tall box beside it. bmatrix exists precisely so the fence and the grid are one object.
    • Words in a cell with no \text. value in a cell is not a word but the product of six italic variables, and it is set tighter and stranger than the text you meant; the same goes for multi-word headers, which want \text{…} and, because cells are text style, occasionally \text{\small …} as well.

    Questions about this lesson

    How do I write an augmented matrix with a vertical line in LaTeX?
    Use the array environment and put the bar in the column specification: \begin{array}{cc|c} ... \end{array} declares two coefficient columns, a rule, and the constants column. The rule is preamble syntax, so re-partitioning is a one-character edit — {c|cc} moves it, and {cc|cc} handles two right-hand sides. A horizontal partition is \hline as its own row. array is the only member of the family that arrives with no delimiters, so put your own brackets around the whole thing, and trim the outer padding with @{} at each end of the preamble if the brackets sit too far from the entries. This form is also the portable one: array with a | and an \hline renders in browser maths display as well as in pdflatex, which package-based labelled matrices do not.
    What is the difference between pmatrix, bmatrix, Bmatrix and matrix in LaTeX?
    Only the delimiter, which is bolted on around an identical grid. matrix has none, pmatrix is round, bmatrix square, Bmatrix curly, vmatrix and Vmatrix single and double bars, and the case of the leading letter is what doubles the fence. They share one grammar — an ampersand separates columns and a double backslash ends rows — and all of them need \usepackage{amsmath}. The choice carries notation meaning rather than appearance: pmatrix for a general matrix, bmatrix for operators and coefficient matrices, vmatrix strictly for determinants, Bmatrix mostly for a set written as a grid. What you should not do is type matrix and add your own brackets: a hand-typed [ is an ordinary maths atom with no idea a tall box is going beside it, so the spacing comes out wrong.
    Why does LaTeX say "Extra alignment tab has been changed to \cr" when I type a matrix?
    Because a row has more cells than the alignment preamble has columns. For an array that means more ampersands in a row than the letters you declared in its column specification. For a matrix environment it usually means you have crossed amsmath's column ceiling: every matrix is built as an array with *\c@MaxMatrixCols c, and MaxMatrixCols defaults to 10, so an eleventh column overruns the preamble. Raise the counter locally — {\setcounter{MaxMatrixCols}{20} ... } — and consider instead whether an eleven-wide grid in a text-width display wants block partitioning, a transpose, or two displays joined by a sentence. The third common cause is a plain miscount: a row whose & count differs from the others, which is worth checking before you change any counter.
    How do I write a diagonal or identity matrix with dots in LaTeX?
    Put each dot in its own cell and keep every row on the same ampersand count — \cdots across a row, \vdots down a column, \ddots along the diagonal — because a dot implies that the grid continues, it does not create rows or columns by itself. A three-by-three skeleton with named entries and the diagonal running through the middle is enough for an n-by-n matrix, and is preferable to a wall of dots: three real entries, one diagonal, and a sentence saying what fills the rest. Never type ... — three baseline periods have punctuation spacing and the wrong height for every direction. amsmath's \dots looks at what follows and chooses the centred or baseline form for you if you would rather not decide, and the rising diagonal has no glyph in the core set, so restructure the matrix or reach for a package that supplies one.
    How do I add row and column labels outside a matrix in LaTeX?
    Outside the fence you need a container that reserves space for them, and there are four candidates with quite different costs. \bordermatrix is plain TeX's: it uses \cr rather than \, draws no brackets, offers no styling control and is not part of the LaTeX kernel. kbordermatrix is a LaTeX-side version of the same thing with the brackets added. blkarray moves you to the ordinary ampersand-and-double-backslash grammar you already know — an outer blockarray plus an inner block whose preamble marks bordered columns with brackets — and is the one that does partial rules properly. nicematrix (NiceMatrix, pNiceMatrix, bNiceMatrix and friends, with first-row and first-col options; older versions used top-header and left-header) is the modern choice, and the only one that gives you headers, fences and rules as one object, but it pulls in TikZ, needs a recent LaTeX and an extra compile pass. None of the four renders in browser-side maths, so the portable answer is to build the labels as ordinary cells of a wider array with a | and an \hline, and supply the brackets yourself.
    Can a LaTeX matrix contain text, and how do I stop it turning into italic variables?
    Yes, in every container, with \text{...} from amsmath: cells are maths mode, so an unwrapped word is typeset as the product of its letters, tighter and slanted. \text{} inherits the surrounding text font and takes you back to normal spacing, which is what header cells and unit labels want; for a label that should stay roman but look like maths, \mathrm{col} is the other option. Two things follow from cells being text style rather than display style: a \frac inside \text is already small, and \text{\small ...} is sometimes needed to stop a word dominating a row of numbers. If the text is long enough to need wrapping, you have stopped setting a matrix — that material belongs in a tabular column with a declared width, or in the sentence around the display.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.