views:

154

answers:

2

Given a 4x4 matrix, what formula could i apply to each (x,y) cell to yield an (x,y) if the matrix was rotated 90 degrees to the right? I tried iterating over each cell but different cells gave different formulas.

Given the following matrix of values.

0|  |  |  |  |
1|  |  |  |  |  
2|  |  |  |  |    
3|  |  |  |  |
 -------------
  0   1  2  3

Rotate the values 90 degrees by moving the value in (x,y) to the (x,y) value in the matching cell using the matrix below:

0 | 0,3 | 0,2  | 0,1 | 0,0 |
1 | 1,3 | 1,2  | 1,1 | 1,0 |  
2 | 2,3 | 2,2  | 2,1 | 2,0 |    
3 | 3,3 | 3,2  | 3,1 | 3,0 |
  --------------------------
     0     1      2     3

ie:

If cell (0,0) has the value 5, 
using the translation matrix 5 would move to (3,0).

Hard-coding this translation matrix is tedious and error prone, and if the matrix size grows to huge numbers doing this by hand is simply retarded.

+3  A: 

If you have an n by n matrix, assuming (i, j) means the ith row and the jth column, for a rotation to the right:

the cell (i, j) will move to (j, n-i)

Here's how you think about it. Picture the entire ith row. When you rotate the matrix, that entire row turns into an entire column. Which one? It'll be i columns from the right, i.e., column n-i.

Now picture the entire jth column. When you rotate, the column turns into row. Which one? It'll be j rows from the top, i.e., row j.

Jesse Beder
That seems to work, thanks!I was only using i an j in my attempted equations causing the results to fluctuate, I guess that n is necessary.
Absolute0
Presumably by "fluctuate" you mean you were also reflecting the matrix.
Jefromi
A: 

Heres an example with C code

http://bytes.com/topic/c/answers/516008-rotate-matrix-any-size

John Ellinwood
That's some ugly code :)Heres how i did it in Java: public void rotate() { for(int i = 0; i < SHAPE_GRID_SIZE; i++) shapePoints_[i] = new Point(shapePoints_[i].y, SHAPE_GRID_SIZE - shapePoints_[i].x); }
Absolute0