Hi, I'm new to C++ and I hope I can find someone to help me here. I have to make a function that rotates the elements of a matrix (with n*m elements) with a multiple of 90 degrees (90, 180, etc)
I've tried lots of things but I couldn't come close to a good result so I'd appreciate some advice.
I tried this:
void rot (int a[50][50], int m, int n, int angle, int b[50][50])
{int i,j,x,y;
for (i=0;i<m;i++)
{for (j=0;j<n;j++)
{y=i*sin(angle)+j*cos(angle);
x=i*cos(angle)-j*sin(angle);
b[x][y]=a[i][j];
}
}
}
Orthogonal rotations only involve copying in different directions.
Let's say we have a matrix 'src_matrix' of width lx and height ly:
Clockwise 90°:
(dst_matrix should have sizes ly and lx)
dst_matrix[y-lx][x]=src_matrix[x][y]
Clockwise 180°:
(dst_matrix should have sizes lx and ly)
dst_matrix[x-lx][y-ly]=src_matrix[x][y]
Clockwise 270° (or counter-clockwise 90°):
(dst_matrix should have sizes ly and lx)
dst_matrix[y][x-ly]=src_matrix[x][y]
Your best bet, actually, would be to do it on paper first.
Get yourself a piece of graph paper and draw a simple matrix:
1 2 3
4 5 6
This is a 3 b 2 matrix. If you rotate 90 degrees, you will need a 2 by 3 matrix:
_ _
_ _
_ _
Now just fill in the appropriate locations
_ _ _ _ 3 _ 3 _ 3 _ 36
_ _ 2 _ 2 _ 2 _ 25251 _ 1 _ 1 _ 141414
Your rotation routines will work very much the same. Keep in mind that, unless you have a square matrix, you will need to create a new matrix to store the results of the rotation.
Hint: consider the relationship between the indices of the old and new matrices.
(This is basically the same thing that helios said.)
[edit] It just occurred to me that I did 90° ccw, which is the same as you do in math, but helios did 90° cw. Keep that in mind...) [/edit]