TITLE: How to rotate a matrix by 45 degrees?
QUESTION [9 upvotes]: Assume you have a 2D matrix.


Ignore the blue squares.
The first image represents the initial matrix and the second represents the matrix rotated by 45 degrees.
For example, let's consider a random cell from the first image.
a32 (row 3, column 2)
Let x be the row and y be the column, so x = 3 and y = 2.
The formula of this rotation is : RM[x + y - 1][n - x + y] = M[x][y], where RM means rotated matrix, M the initial matrix, and n the dimension of the initial matrix (which is n x n).
So, a32, from the third row and second column will get to the fourth row and the fourth column.
The problem is, I don't really understand this forumla. Can you help me?
And how do you rotate by 45 degrees a matrix that is not square shaped? (a rectangle shaped one)
Any help is much appreciated.
Thank you very much!

REPLY [2 votes]: Let me explain it in my words.First of all, that is not exactly the mathematical definition of rotation, it is looking more like an image processing operator with predefined pixels position (matrix cells).
We have to define a couple of thinks:

the center of rotation: let say it the the cell of indexes ic and jc (for center). It happens to be the exact middle cell in the example, thanks to the odd size of the square matrix. It wont be the same for even sized matrix, and will get a little more tricky for rectangular matrix. Let us not think about angle not multiple of 45 degrees.
position relative to the center of rotation: Let's add new indexes that define the offset with respect to the center of rotation; for the cell (i,j), this offset is (i-ic, j-jc).

Now, if you think about it, you will find that for a 45 degrees rotation, rows above the center (row with index i less than ic) shift to the right by (ic-i) cells. For rows bellows ic (i>ic) they shift to the left by (i-ic) cells. A general formula for the shift is simply -(i-ic) with right shift for positive number and left shift for negative. This is a shift in column, so an offset in rows induces a shift in column.
for columns we will have something similar, an offset in column will induce shift in rows. The shift in this case is (j-jc), no negative sign. Now, positive shift means shift down and negative means shift up.
Now, let suppose that we can guess the position of the rotated center irc, jrc, the offset of cell (i,j) in the rotated matrix is simply:

ir - irc = i - ic + (j-jc) = i + j - (ic + jc)
jr - jrc = j - jc - (i-ic) = j - i + (ic - jc)

So you get 

ir = i + j + irc - (ic + jc)
jr = j - i + jrc + (ic - jc)

It is simple to determine the position of the center, it is the position that guarantees the min col is 1 and the min row is 1 (in one based indexation).
It is easy to check that the formula hold for your example. n = 2k+1 and ic = jc = k+1.