# Arrows labeled with matrices in tikz-cd

I want to write a commutative diagram with tikz where some arrows are labeled with matrices. I know that nesting creates problems in tikz, and I don't know how to handle this. I usually put the commands for arrows into square brakets, e.g. in the following way

\arrow[r, hook, "f"]


Now I have come up with a tentative solution, but this does not work writing it with square brakets for some reasons. So I must use curly ones. But with the latter, I can't move the label, so they overlap. How can I move the labels outside the diagram? (Or increase the space between columns, or any other solution, but I would prefer also to know how to swap side for the labels when writing with curly brakets)

Here is a MWE:

\documentclass[a4paper,11pt,twoside]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}
\usepackage{graphicx, tikz-cd}
\usepackage{indentfirst}
\usepackage{amsmath,amssymb, mathtools}
\usepackage{microtype}
\begin{tikzcd}[ampersand replacement=\&]
A_n\oplus A_{n-1} \arrow{r}{\begin{psmallmatrix} d_n^A & (-1)^n \\ 0 & d_{n-1}^A \end{psmallmatrix}} \arrow{d}{\begin{psmallmatrix} 0 & 1 \\ f_n & 0 \end{psmallmatrix}}
\&A_{n-1}\oplus A_{n-2}\arrow{d}{\begin{psmallmatrix} 0 & 1 \\ f_n & 0 \end{psmallmatrix}}
\\
A_{n-1} \oplus B_n \arrow{r}{\begin{psmallmatrix} -d^A_{n-1} & 0 \\ f_{n-1} & d^B_n \end{psmallmatrix}}
\& A_{n-2} \oplus B_{n-1}
\end{tikzcd}


You need ampersand replacement because otherwise & in the matrices will not work.

Just increase the column and row separation in order that the big labels fit.

The further trick is to use "{\begin{bsmallmatrix}...\end{bsmallmatrix}}" with surrounding braces so that the parser is not confused.

\documentclass[a4paper,11pt,twoside]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}
\usepackage{graphicx, tikz-cd}
\usepackage{indentfirst}
\usepackage{amsmath,amssymb, mathtools}
\usepackage{microtype}

\begin{document}

\begin{tikzcd}[ampersand replacement=\&,column sep = 6em, row sep=3em]
A_n\oplus A_{n-1}
\arrow[r,"{\begin{bsmallmatrix} d_n^A & (-1)^n \\ 0 & d_{n-1}^A \end{bsmallmatrix}}"]
\arrow[d,"{\begin{bsmallmatrix} 0 & 1 \\ f_n & 0 \end{bsmallmatrix}}"']
\&
A_{n-1}\oplus A_{n-2}
\arrow[d,"{\begin{bsmallmatrix} 0 & 1 \\ f_n & 0 \end{bsmallmatrix}}"]
\\
A_{n-1} \oplus B_n
\arrow[r,"{\begin{bsmallmatrix} -d^A_{n-1} & 0 \\ f_{n-1} & d^B_n \end{bsmallmatrix}}"]
\& A_{n-2} \oplus B_{n-1}
\end{tikzcd}

\end{document}


Just for comparison..with tikz-cd using xy package...

\documentclass[a4paper,12pt]{article}
\usepackage[all,cmtip]{xy}
\usepackage{mathtools}
\begin{document}
$\xymatrix@C=6pc{ A_{n}\oplus A_{n-1} \ar[d] \ar[r]^{\begin{bsmallmatrix} d_{n}^{A} & (-1)^{n} \\ 0 & d_{n-1}^{A} \end{bsmallmatrix}} & A_{n-1}\oplus A_{n-2} \ar[d] \\ A_{n-1} \oplus B_{n} \ar[r]^{\begin{bsmallmatrix} -d^A_{n-1} & 0 \\ f_{n-1} & d^B_n \end{bsmallmatrix}} & A_{n-2} \oplus B_{n-1}}$
\end{document}