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.
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;
        }
}
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;
        }       
}
Try a simple 3x3 matrix first. You only have to access (N^2 - N)/2 elements.
Here is a visual.
   0 1 2
0  * * /
1  * / x
2  / x x
You only need to access (9-3)/2 = 3 elements. Specifically (0,0),(0,1), and (1,0), so a nested loop for N = 3 should look something like
for(int i = 0; i < 2; i++)
    for(int j = 0; j < 2-i; j++)
        //etc..
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With