Switching the position of matrix elements in Mathematica

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
Qubix
Messages
82
Reaction score
1
Say I have the following matrix, written in Mathematica

A := {{a11, a12, a13, a14}, {a21, a22, a23, a24}, {a31, a32, a33,
a34}, {a41, a42, a43, a44}}

I want to exchange the positions of a12 and a21, a14 and a23, a32 and a41 , a34 and a43.

Any ideas?

Thanks.
 
Physics news on Phys.org
Notice it you broke A into four 2x2 matricies, did a Transpose of each submatrix and reassembled the result back into a full matrix you would have what you want. But I can't think of a cute trick to split the matrix apart.

Either that or just brute force it
Code:
In[1]:= A={
   {a11, a12, a13, a14},
   {a21, a22, a23, a24},
   {a31, a32, a33, a34},
   {a41, a42, a43, a44}};
For[r=1, r<=3, r+=2,
  For[c=1, c<=3, c+=2,
   {A[[r+1, c]], A[[r, c+1]]} = {A[[r, c+1]], A[[r+1, c]]}
   ]
  ];
A

Out[3]= {
 {a11, a21, a13, a23},
 {a12, a22, a14, a24},
 {a31, a41, a33, a43},
 {a32, a42, a34, a44}}