Let us say that I have a $3 \times 3$ matrix $\bf X$, that has to be reshaped into a vector and rearranged as follows:
$$ {\bf v} ({\bf X}) = \begin{bmatrix} x_{22} & (x_{23}+x_{32}) & (x_{21}+x_{12}) & x_{33} & (x_{13}+x_{31}) & x_{11} \end{bmatrix} $$
where the indices indicate the position of the elements in the matrix $\bf X$. How to do this rearrangement automatically for any size of matrix $\bf X$?
The ${\bf v} ({\bf X})$ represents the coefficients of monomials of a vector $y = \begin{bmatrix} a_1 & a_2 & b\end{bmatrix}^T$ of degree 2 i.e. the elements of ${\bf v} ({\bf X})$ are coefficients of $z = \begin{bmatrix} a_1^2 & a_1a_2 & a_1b & a_2^2 & a_2b & b^2 \end{bmatrix}^T$. So, the matrix ${\bf X}$ contains coefficients of z in a fashion that, the diagonal elements are monomials without cross product and the off-diagonal elements are monomials with two variable.
$$ {\bf X} = \operatorname{coeff} \left( \begin{bmatrix} b^2 & \frac{a_1b}{2} & \frac{a_2b}{2} // \frac{a_1b}{2} & a_1^2 & \frac{a_1a_2}{2} // \frac{a_2b}{2} & \frac{a_1a_2}{2} & a_2^2\end{bmatrix} \right).$$
For $y = \begin{bmatrix} a_1 & a_2 & a_3 & b\end{bmatrix}^T$ and degree 2, $z = \begin{bmatrix} a_1^2 & a_1a_2 & a_1a_3 & a_1b & a_2^2 & a_2a_3 & a_2b & a_3^2 & a_3b & b^2 \end{bmatrix}^T$ and the matrix ${\bf X}$ will be of size $4 \times 4$.