简体   繁体   English

关于二次对角线的转置(翻转)矩阵

[英]Transpose (flip) matrix about secondary diagonal

I'm trying to write a program to transpose a square matrix about it's secondary diagonal.我正在尝试编写一个程序来转置一个关于它的二次对角线的方阵。 I know how to transpose it normally (Along it's normal diagonal), but I am not able to figure out how to do it about the secondary axis.我知道如何正常转置它(沿着它的正常对角线),但我无法弄清楚如何围绕辅助轴进行转置。

What is wrong in the loop?循环中有什么问题? I know that I have to run it till 'N/2' and change the initialization of 'i' and 'j', it does not work even if I do that though.我知道我必须运行它直到“N/2”并更改“i”和“j”的初始化,即使我这样做也不起作用。

void transpose(int a[][N]) // Transposes matrix along the secondary diagonal 
{
    for (int i = 0; i < N; i++)
        for (int j = 0; j < i; j++)
        {
            int tmp = a[i][j];
                a[i][j] = a[N - 1 - j][N - 1 - i];
                a[N - 1 - j][N - 1 - i] = tmp;
        }

}

Try a simple 3x3 matrix first.首先尝试一个简单的 3x3 矩阵。 You only have to access (N^2 - N)/2 elements.您只需要访问 (N^2 - N)/2 个元素。

Here is a visual.这是一个视觉效果。

   0 1 2
0  * * /
1  * / x
2  / x x

You only need to access (9-3)/2 = 3 elements.您只需要访问 (9-3)/2 = 3 个元素。 Specifically (0,0),(0,1), and (1,0), so a nested loop for N = 3 should look something like特别是 (0,0)、(0,1) 和 (1,0),所以 N = 3 的嵌套循环应该看起来像

for(int i = 0; i < 2; i++)
    for(int j = 0; j < 2-i; j++)
        //etc..

Hope this helps.希望这会有所帮助。

So, I figured out the loop after a lot of time.所以,我在很长一段时间后找到了循环。 The correct code should access the upper triangular elements in the square matrix, and swap them with the corresponding elements in the lower triangular matrix.正确的代码应该访问方阵中的上三角元素,并将它们与下三角矩阵中的相应元素交换。 The secondary diagonal is left unchanged.第二对角线保持不变。

Here is the tested, working code:这是经过测试的工作代码:

void swapEl(int mat[][n])
{
    for (int i = 0; i < (n - 1); i++)
        for (int j = 0; j < (n - 1) - i; j++)
        {
            int tmp = mat[i][j];
                mat[i][j] = mat[(n - 1) - j][(n - 1) - i];
                mat[(n - 1) - j][(n - 1) - i] = tmp;
        }       
}

The code accesses the upper triangular elements in the square matrix and swaps them with the corresponding element in the lower triangular matrix. 该代码访问方矩阵中的上三角元素,并将它们与下三角矩阵中的相应元素交换。 The secondary diagonal is left unchanged. 辅助对角线保持不变。

for(int i=0;i<(n-1);i++)
{
    for(int j=0;j<(n-i-1);j++)
    {
        int t = a[i][j];
        a[i][j] = a[n-j-1][n-i-1];
        a[n-j-1][n-i-1] = t;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM