Using Perl PDL to rotate a matrix

I would like to use Perl and PDL to achieve 3x3 matrix rotation (if possible)

I. original matrix

[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]

I would like to rotate around 5 so that it becomes a new matrix

[ 3, 6, 9 ]
[ 2, 5, 8 ]
[ 1, 4, 7 ]

In fact, this is the same as How do you rotate a two-dimensional array? but I would like to use Perl and PDL.

Thank you for your help.

+4
source share
3 answers

This may not be the most optimized way:

pdl> $m = sequence(3,3)+1
pdl> p $m

[
 [1 2 3]
 [4 5 6]
 [7 8 9]
]

pdl> p $m->transpose->slice( ':', '-1:0' )

[
 [3 6 9]
 [2 5 8]
 [1 4 7]
]
+10
source

Stupid matrix tricks

, , , . , pdl ( , ), , , , .

W :

    [0 0 1]
W = [0 1 0]
    [1 0 0]

W - -. ( , W S, .) 3x3 M W x M, M. M x W ( ), M.

, :

        [0 0 1]   [1 2 3]   [7 8 9]
W x M = [0 1 0] x [4 5 6] = [4 5 6]
        [1 0 0]   [7 8 9]   [1 2 3]

, 90 & deg; , , (M' M -):

         [0 0 1]   [1 4 7]   [3 6 9]
W x M' = [0 1 0] x [2 5 8] = [2 5 8]
         [1 0 0]   [3 6 9]   [1 4 7]

, M x W M:

        [1 2 3]   [0 0 1]   [3 2 1]
M x W = [4 5 6] x [0 1 0] = [6 5 4]
        [7 8 9]   [1 0 0]   [9 8 7]

W x M'! , :

         [1 4 7]   [0 0 1]   [7 4 1]
M' x W = [2 5 8] x [0 1 0] = [8 5 2]
         [3 6 9]   [1 0 0]   [9 6 3]

M 90 & deg; . W x M.

90 & deg; :

Rotate counterclockwise: W  x M' = (M x W)'  
Rotate clockwise:        M' x W  = (W x M)'

, , 180 & deg; , :

            [0 0 1]   [1 2 3]   [0 0 1]   [7 8 9]   [0 0 1]   [9 8 7]
W x M x W = [0 1 0] x [4 5 6] x [0 1 0] = [4 5 6] x [0 1 0] = [6 5 4]
            [1 0 0]   [7 8 9]   [1 0 0]   [1 2 3]   [1 0 0]   [3 2 1]

, , , , , .

+5

I also do not understand PDL, but if you can "cut" the 2d matrix into a "virtual", 9-element vector that looks like a quick reading of the documentation, then you can implement any permutation (including rotation) of the original 3x3 as a 9x9 permutation matrix , multiply the 1d slice by this matrix and then refer to the original 3x3 pdl to see the result.

If I have time, I will try to find out enough PDL to test this idea.

0
source

Source: https://habr.com/ru/post/1524290/


All Articles