Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
2  
Ponder on Join @@ Table[-Differences[Diagonal[G, k]], {k, {0, 1, -1}}]. –  J. M. Jun 3 '13 at 17:10
    
@0x4A4D : Exactly what I was looking for. Thank you! –  guest Jun 3 '13 at 17:21
add comment

2 Answers 2

up vote 2 down vote accepted
k = Table[g[i, j], {i, 4}, {j, 4}]; 
Flatten[Diagonal[k[[;; -2, ;; -2]] - k[[2 ;;, 2 ;;]], #] & /@ {0, 1, -1}]
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.