# How to transform this matrix & swap its columns in a simple way?

I would like to transform matrix $\mathbf A = \begin{pmatrix} a&b&i&j\\ c&d&k&l \\ e&f&m&n \\ g&h&o&p \end{pmatrix}$ into matrix $\mathbf B = \begin{pmatrix} -p&o&-h&g\\ -n&m&-f&e \\ -l&k&-d&c \\ -j&i&-b&a \end{pmatrix}$.

If possible I would like to generalize this to $\{n\times n,\ n>4\}$ size matrices. Is there a simple way to do this in Mathematica?

-
Please do provide at least A as a Mathematica expression. –  Yves Klett Feb 17 '13 at 15:50

Surely a better solution exists! Assuming m your matrix.

m = RandomReal[1, {1000, 1000}];
pat = Array[(-1)^# &, First@Dimensions[m]];
B1 = (pat #) &  /@ Reverse[m, {1, 2}]; // AbsoluteTiming


{0.124800, Null}

Though Table is intuitive but will be pretty slow for big lists.

u = Length[m];
B = Table[
m[[u - r, u - s]]*(-1)^(s + 1), {r, 0, u - 1}, {s, 0,u - 1}]; // AbsoluteTiming


{6.567611, Null}

Testing!

B2 === B


True

Now if you want to go even faster with Mathematica use Compile to external language C. However this is a solution only if your matrix has Number entries. However you will not get much more speed up as Map and Reverse are already pretty optimized in Mathematica.

fun = Compile[{{x, _Real, 2}}, Module[{pat},
pat = Array[(-1)^# &, First@Dimensions[x]];
(pat #) &  /@ (Reverse[Reverse /@ x])],
CompilationTarget -> "C"];
B3 = fun[m]; // AbsoluteTiming


{0.062400, Null}

Testing again!

B === B2 === B3


True

-
Ok! This works fine, and you sure are convincing! Thanks a lot! –  jrojasqu Feb 17 '13 at 14:38

How do you like this?

A = {{a, b, i, j}, {c, d, k, l}, {e, f, m, n}, {g, h, o, p}};
B = Reverse[A,{1,2}].DiagonalMatrix[{-1, 1, -1, 1}]

-
Thanks for your contribution! How can we generalize your proposition for large matrices? –  jrojasqu Feb 17 '13 at 14:42
@jrojasqu change the list inside the diagonal matrix to (-1)^Range@Length@A –  The Toad Feb 17 '13 at 14:59

Ok,

I feel sorry for myself by now... This was easier than I thought... So here's my proposition for a solution :

Given matrix $\mathbf A$ written in mathematica as :

A = {{a, b, i, j}, {c, d, k, l}, {e, f, m, n}, {g, h, o, p}}


To obtain matrix $\mathbf B$ I did this :

u = Length[A];
B = Table[A[[u - r, u - s]]*(-1)^(s + 1), {r, 0, u-1}, {s, 0, u-1}]


There it is, I hope this proves useful to someone.

-
u = Length@A instead –  Öskå Feb 17 '13 at 12:38
@Öskå You're absolutely right, this code can be highly optimized, it's just that I posted it as soon as it came to me... –  jrojasqu Feb 17 '13 at 12:42
 ClearAll[trnsfrmF1, trnsfrmF2];
trnsfrmF1 = MapAt[-# &, Reverse /@ Reverse@#, {;; , ;; ;; 2}] &;
trnsfrmF2 = Module[{temp = Reverse /@ Reverse@#},
temp[[;; , ;; ;; 2]] = (-1) temp[[;; , ;; ;; 2]]; temp] &;


Example usage:

 aa = ArrayReshape[CharacterRange["a", "p"], {4, 4}];
Grid[{{"aa", "trnsfrmF1[aa]", "trnsfrmF2[aa]"},
MatrixForm /@ {aa, trnsfrmF1[aa], trnsfrmF2[aa]}}, Dividers -> All]


-