# How to Code Adjacency Matrix

do you know how to code this in latex?

• what did you try so far? Apr 17 at 10:18
• Welcome. // There were already similar questions here. Search for nicematrix . Apr 17 at 10:25

with nicematrix, it's super easy

\documentclass{article}
\usepackage{nicematrix}

\begin{document}

$\mathbf{A}_H = \begin{bNiceMatrix}[first-row,first-col] & v_6 & v_3 & v_4 & v_5 & v_1 & v_2 \\ v_6 & 0 & 1 & 0 & 1 & 0 & 0 \\ v_3 & 1 & 0 & 1 & 0 & 0 & 1 \\ v_4 & 0 & 1 & 0 & 1 & 0 & 0 \\ v_5 & 1 & 0 & 1 & 0 & 1 & 0 \\ v_1 & 0 & 0 & 0 & 1 & 0 & 1 \\ v_2 & 0 & 1 & 0 & 0 & 1 & 0 \\ \end{bNiceMatrix}$

\end{document}

• Nice, but you're conditioning a new user on "wrong" behaviour: we'd like to see own attempts ;-) Apr 17 at 11:35
• @MS-SPO I cannot disagree. My bad. But the answer was so straighforward...
– JeT
Apr 17 at 12:21
• No problem ... happens to all of us every now and then ... Apr 17 at 12:30

This is an interesting problem. Here I define a data structure for graphs, providing for printing the adjacency matrix, but we can imagine other uses.

The idea is to store the indices for the vertices in a sequence and the list of edges in another sequence.

The vertex list is mapped (twice) to check whether a given edge is in the edge list; in this case 1 is added to the body of the matrix, otherwise 0.

Using nicematrix allows to also fill the outer row and column.

\documentclass{article}
\usepackage{nicematrix}

\ExplSyntaxOn

\NewDocumentCommand{\definegraph}{mmm}
{% #1 = graph name, #2 = vertex list, #3 = edge list
\ryl_graph_define:nnn { #1 } { #2 } { #3 }
}

{% #1 = graph name
}

\cs_new_protected:Nn \ryl_graph_define:nnn
{
\seq_clear_new:c { l__graph_vertex_#1_seq }
\seq_set_from_clist:cn { l__graph_vertex_#1_seq } { #2 }
\seq_clear_new:c { l__graph_edge_#1_seq }
\seq_set_from_clist:cn { l__graph_edge_#1_seq } { #3 }
}

{
\seq_map_inline:cn { l__graph_vertex_#1_seq }
{
\tl_put_right:Nn \l__ryl_graph_adjacency_tl { & v\sb{##1} }
}
\seq_map_inline:cn { l__graph_vertex_#1_seq }
{
\seq_map_inline:cn { l__graph_vertex_#1_seq }
{
\seq_if_in:cnTF { l__graph_edge_#1_seq } { ##1-####1 }
{% the edge is in
\tl_put_right:Nn \l__ryl_graph_adjacency_tl { & 1 }
}
{
\seq_if_in:cnTF { l__graph_edge_#1_seq } { ####1-##1 }
{% the edge is in
\tl_put_right:Nn \l__ryl_graph_adjacency_tl { & 1 }
}
{
\tl_put_right:Nn \l__ryl_graph_adjacency_tl { & 0 }
}
}
}
}
\begin{bNiceMatrix}[first-row,first-col]
\end{bNiceMatrix}
}

\ExplSyntaxOff

\definegraph{A}{1,2,3}{1-2,1-3,2-3}
\definegraph{B}{6,3,4,5,1,2}{6-3,6-5,3-6,3-4,3-2,4-3,4-5,5-1,1-2}

\begin{document}

$\adjacencymatrix{A}$

$\mathbf{A}_{H}=\adjacencymatrix{B}$

\end{document}


In the second example, you can see that listing duplicate edges is irrelevant.

• Very good code, as usual. Maybe \definegraph{B}{6,3,4,5,1,2}{6:3-5,3:6-4-2,4:3-5,5:1,1:2} would be a better API. Apr 17 at 15:20
• @projetmbc I don't think so: edges are charcterized by their two ends. Apr 17 at 16:52