I'm not sure if this question has been either asked or quite possibly already answered. If I start with an original 3x3 matrix:
1 2 3 4 5 6 7 8 开发者_开发知识库9
, how would I produce the following 3x3 matrix:
9 6 3 8 5 2 7 4 1
??
For an N*N square matrix :
for(int i=0;i<n-1;i++)
for(int j=0;j<n-1-i;j++) //Swap elements above anti-diagonal
std::swap(mat[i][j],mat[n-1-j][n-1-i]); //with elements below it
Since you're trying to reflect about the secondary diagonal (that's NOT transposition), here's the code, a slightly modified copy of Peter's:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
int temp = a[i][j];
a[i][j] = a[n - 1 - j][n - 1 - i];
a[n - 1 - j][n - 1 - i] = temp;
}
}
For a reflection, pairs of items in the matrix are swapped, so the "do something" (within the loops) will be a swap operation. Loops will be used to pick an item to swap, and some basic arithmetic is used to choose which item to swap it with. The loops should iterate over the triangle of items that are one side of the axis to reflect around, excluding those on the reflection axis and on the other side of it. To visualise that...
0 1 2
0 * * /
1 * / .
2 / . .
The asterisks are the items to use as first parameters for the swap. The dots are the items to use as second parameters to the swap. The slashes are on the reflection axis.
Therefore...
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (n-1)-i; j++) // Thanks to Bugaboo for bugfix
{
std::swap (a[i][j], a[2-j][2-i]);
}
}
With a 3x3 matrix, the loops are a bit excessive - they are shown here for the principle, and to show how to extend it. There are only three asterisks in that visualisation, and only three swap operations needed...
std::swap (a[0][0], a[2][2]);
std::swap (a[0][1], a[1][2]);
std::swap (a[1][0], a[2][1]);
I think I found a way in the MatLab that combines a series of other existing flipping method.
- fliplr (flip left and right)
- transpose
- fliplr
Ham
is the target then the code is the following.
Maybe it is wrong, but let me know.
fliplr(fliplr(Ham)')
精彩评论