4

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?

Thanks in advance.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Meclassic
  • 1,005
  • 1
  • 9
  • 15

4 Answers4

7

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

PlatoManiac
  • 14,723
  • 2
  • 42
  • 74
5

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}]
yulinlinyu
  • 4,815
  • 2
  • 29
  • 36
1

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.

Meclassic
  • 1,005
  • 1
  • 9
  • 15
0
 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]

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896