quant
quant

Reputation: 23022

How can I mirror a matrix about one of its dimensions?

I am using Eigen, but since eigen uses basic maths operators this is basically just a maths question. Here is the pseudo-code for what I am after:

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

            [7 8 9]
A.flipv() = [4 5 6]
            [1 2 3]

How could I achieve something like this in Eigen? (I'm using version 3.2)

EDIT: I think what I want to do here is swap the top rows with the bottom rows (some combination of .topRows(), .bottomRows() and .swap()?)

Upvotes: 4

Views: 7716

Answers (3)

ggael
ggael

Reputation: 29205

If you want a general flip, i.e., not only for a 3x3 matrix, then the reverse() function is what you're looking for. In particular A.colwise().reverse() will reverse each column thus doing a vertical flip. For an horizontal flip: A.rowwise().reverse().

Upvotes: 11

Johan Lundberg
Johan Lundberg

Reputation: 27038

You just need to multiply with another 3x3 matrix with zeros and ones in the right places. I think you can solve it using pen and paper from there. I'll give you a hint: there are just 3 ones in the solution.

.. All right:

[0 0 1]
[0 1 0]
[1 0 0]

Upvotes: 6

Lajos Arpad
Lajos Arpad

Reputation: 76424

I can give you two possible solutions:

1.

If you have n rows in your matrix, you can do the following: For any element in the first n/2 rows, let's suppose it is on the i'th row and j'th column and we index the rows and columns from 0, then you can swap M[i, j] with M[n - 1 - i, j] and the result will be just as described.

2.

The second solution is Johan Lundberg's solution:

Let's consider the matrix of

0 0 1
0 1 0
1 0 0

I x M results in the matrix you have desired. For example:

0 0 1   1 2 3   7 8 9
0 1 0 x 4 5 6 = 4 5 6
1 0 0   7 8 9   1 2 3

Upvotes: 3

Related Questions