Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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;
        }

}
like image 901
MinorMapillai Avatar asked Oct 28 '25 08:10

MinorMapillai


2 Answers

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;
        }       
}
like image 182
MinorMapillai Avatar answered Oct 31 '25 07:10

MinorMapillai


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.

like image 37
SomeGuy Avatar answered Oct 31 '25 06:10

SomeGuy