macro to create Square matrix of order 4

I have created a macro to write a matrix of order 3 (square matrix) using the following code

 \newcommand{\matrixthree}[9]{$\left(\begin{matrix} #1 & #2 & #3 \\ #4 & #5 & #6 \\ #7 & #8 & #9 \end{matrix}\right)$}


But I am unable to create a macro with 16 parameters (elements) for a square matrix of order two which has 16 elements.

Is there a way! or better way. Thanks!

• Possible duplicate: How do I construct an n by n matrix. My answer to that question, involving sagetex is easy but relies on SAGE. It also gives you the power to generate identity matrices, nonsingular matrices, as well as handle matrix multiplication, transposes and more. See my answer here for transposes and multiplication.
– DJP
Commented Jul 26, 2019 at 14:55
• @DJP The linked question is about producing a random matrix. Commented Jul 26, 2019 at 15:41

I'm not sure whether \matrixthree{a}{b}{c}{d}{e}{f}{g}{h}{i} is really easier than

\begin{pmatrix} a & b & c \\ d & e & f \\ g & h & i \end{pmatrix}


Anyway, here's a command with a simpler interface: rows are separated by \\, entries in each row by a comma. The optional argument is for the fences: p (default) for parentheses, b for brackets, v for bars, V for double bars, B for braces. With \buildmatrix[]{1,2\\3,4} you get no delimiter.

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\buildmatrix}{O{p}m}
{
\begin{#1matrix}
% separate the rows and process each row at a time
\seq_set_split:Nnn \l_tmpa_seq { \\ } { #2 }
\seq_map_function:NN \l_tmpa_seq \__nichas_matrix_row:n
\end{#1matrix}
}

\cs_new_protected:Nn \__nichas_matrix_row:n
{
% split the row at commas
\seq_set_split:Nnn \l_tmpb_seq { , } { #1 }
% insert & between each item
\seq_use:Nn \l_tmpb_seq { & }
% end the row
\\
}
\ExplSyntaxOff

\begin{document}

$\buildmatrix[b]{a,b,c \\ d,e,f \\ g,h,i }\ne \buildmatrix{1,2,3,4 \\ 5,6,7,8 \\ 9,10,11,12 \\ 13,14,15,16 }$

\end{document}