I am writing a function to reverse a matrix and join the reversed version to the original one, making a new matrix which I call A
. And after doing this, I reverse A
and join it with original A
to get the result I want.
I have written my code like this:
matJoin[mat_?MatrixQ] :=
Module[{A, W, H},
A = Join[mat, Reverse /@ mat, 2];
{W, H} = Dimensions[mat];
Join[A, ArrayReshape[Reverse @ Flatten[A], {H, 2 W}]]]
For example, for a random matrix mat=RandomInteger[10, {4, 4}]
shown as below:
{{10, 0, 3, 6}, {1, 0, 1, 9}, {2, 2, 6, 9}, {4, 5, 7, 4}}
Applying it to the matJoin
function I wrote: matJoin[mat]
The output was shown as below and it had served my purpose:
{{10, 0, 3, 6, 6, 3, 0, 10}, {1, 0, 1, 9, 9, 1, 0, 1}, {2, 2, 6, 9, 9, 6, 2, 2}, {4, 5, 7, 4, 4, 7, 5, 4}, {4, 5, 7, 4, 4, 7, 5, 4}, {2,
2, 6, 9, 9, 6, 2, 2}, {1, 0, 1, 9, 9, 1, 0, 1}, {10, 0, 3, 6, 6, 3,
0, 10}}
But my problems are:
- It only works for matrices with dimensions of even orders. If the
W
andH
have odd values, the code doesn't work properly. - I am thinking there is a better way to write the function to make it run faster.
Looking forward to your help.