# Writing “stochastic matrices” in LaTeX

I'm having some notes on stochastic processes and would like to know if there is a less painful way to build stochastic matrices in LaTeX. By painful I want to continue the way I did below.

Question. Is there a more straightforward and economical way to write stochastic matrices in LaTeX? Stochastic matrices have indices above and to the left of matrz aligned with the rows and columns of the matrix. The only way I found to make such an array is by manually adjusting the alignment as in the code below.

$$\begin{array}{cc ccc c ccc c} & & \hspace*{-5mm}1 & 2 & 3 & \cdots & b-2 & b-1 & b \\ \\ \begin{array}{c} 0\\1\\2\\\vdots \\ \\\vdots \\ b-1 \\ b \end{array} & \left[ \begin{array}{c} \\ \\ \\ \\ \\ \\ \\ \\ \end{array} \right. &\hspace*{-4mm} \begin{array}{c} 1\\q\\0\\\vdots \\ \\\vdots \\ 0 \\ 0 \end{array} & \begin{array}{c} 0\\r\\q\\\vdots \\ \\\vdots \\ 0 \\ 0 \end{array} & \begin{array}{c} 0\\0\\p\\\vdots \\ \\\vdots \\ 0 \\ 0 \end{array} & \begin{array}{c} \cdots \\ \cdots\\ \cdots \\\vdots \\ \\\vdots \\\cdots\\ \cdots \end{array} & \begin{array}{c} 0 \\ 0\\ 0 \\\vdots \\ \\\vdots \\q\\ 0 \end{array} & \begin{array}{c} 0 \\ 0\\ 0 \\\vdots \\ \\\vdots \\r\\ 0 \end{array} & \begin{array}{c} 0 \\ 0\\ 0 \\\vdots \\ \\\vdots \\p\\ 1 \end{array} &\hspace*{-4mm} \left. \begin{array}{c} \\ \\ \\ \\ \\ \\ \\ \\ \end{array} \right] \end{array}$$


With blkarray you still need some adjustments, not so much as with your code.
\documentclass{article}
$\begin{blockarray}{ *{8}{c} } & 1 & 2 & 3 & \dots & b-2 & b-1 & b \\ \begin{block}{ c @{\quad} [ @{\,} *{7}{c} @{\,} ] } 0 & 1 & 0 & 0 & \dots & 0 & 0 & 0 \smash[b]{\vphantom{\Big|}} \\ 1 & q & r & 0 & \dots & 0 & 0 & 0 \\ 2 & 0 & q & p & \dots & 0 & 0 & 0 \\ \vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\ b-1 & 0 & 0 & 0 & \dots & q & r & p \\ b & 0 & 0 & 0 & \dots & 0 & 0 & 1 \smash[t]{\vphantom{\Big|}} \\ \end{block} \end{blockarray}$