# Specific rearrangement of elements in list

I have an $n\times n$ matrix G with elements g[i,j] that I construct with Table[g[i, j], {i, 1, n}, {j, 1, n}]

I have tried without success to write a code without loops in Mathematica that rearranges these elements to a vector in a certain way.

To illustrate the case $n=4$: $$G=\begin{pmatrix} g[1,1]&g[1,2]&g[1,3]&g[1,4]\\g[2,1]&g[2,2]&g[2,3]&g[2,4]\\g[3,1]&g[3,2]&g[3,3] &g[3,4]\\g[4,1]&g[4,2]&g[4,3]&g[4,4]\end{pmatrix} \longrightarrow \begin{pmatrix} g[1,1]-g[2,2]\\g[2,2]-g[3,3]\\g[3,3]-g[4,4]\\g[1,2]-g[2,3]\\g[2,3]-g[3,4]\\g[2,1]-g[3,2]\\g[3,2]-g[4,3] \end{pmatrix} = \widetilde{G}$$

I.e, I'm trying to find a way to create a vector where every element is a subtraction between two diagonally consecutive elements in $G$, starting on the central diagonal, working its way to the right and then starting over under the central diagonal working its way to the left. For a fixed $n$ this could easily be done manually, but with my limitations in Mathematica I have not found a way to do this with arbitrary integers.

-
Ponder on Join @@ Table[-Differences[Diagonal[G, k]], {k, {0, 1, -1}}]. –  Ｊ. Ｍ. Jun 3 '13 at 17:10
@0x4A4D : Exactly what I was looking for. Thank you! –  guest Jun 3 '13 at 17:21

k = Table[g[i, j], {i, 4}, {j, 4}];
Flatten[Diagonal[k[[;; -2, ;; -2]] - k[[2 ;;, 2 ;;]], #] & /@ {0, 1, -1}]

-

Since it seems to suit the OP's needs:

G = Array[g, {4, 4}];
Join @@ Table[-Differences[Diagonal[G, k]], {k, {0, 1, -1}}]
{g[1, 1] - g[2, 2], g[2, 2] - g[3, 3], g[3, 3] - g[4, 4], g[1, 2] - g[2, 3],
g[2, 3] - g[3, 4], g[2, 1] - g[3, 2], g[3, 2] - g[4, 3]}


The key here is the use of Diagonal[] to extract the diagonals of a matrix (note the second argument for picking which diagonal to extract), and the use of Differences[] to generate the needed entries; however, the sign is opposite from what the OP needed, so we perform a negation afterwards. Join[] merely strings together the three diagonals thus extracted into a single list.

-