排列主对角线上的条目

Permuting Entries in main Diagonal

如果我有8*8矩阵。具有以下值

希望它像下面这样排列

这样对角线就分为上下两部分。第一个条目 1 填充在底部的第一个位置。第二个条目 2 位于顶部的第一个位置,依此类推。

我想将这个想法扩展到矩阵的其他对角线。

for(int row = 0; row < dimension; row++){ for(int col = 0; col < dimension; col++){ if(row == col){ // Do something to this cell. } } }

我认为最直接的解决方案是先将对角线值保存到附加数组中,然后将其元素循环复制到它们的位置。

C 中的可能解决方案:

int top = 0; // Index where the top part currently is
int bottom = SIZE/2; // Index where the bottom part currently is
int diagonal[SIZE]; // Additional array, which stores the diagonal elements

for(int i = 0; i < SIZE; i++)
    diagonal[i] = matrix[i][i]; // Fill the additional array with diagonal elements

for(int i = 0; i < SIZE; i++)
{
    if(i%2 == 0) // put it to lower part
    {
        matrix[bottom][bottom] = diagonal[i];
        bottom++; // Update the bottom index
    }

    else // put it to upper part
    {
        matrix[top][top] = diagonal[i];
        top++; // Update the top index
    }
}

请注意,SIZE 必须是偶数,才能使其像您描述的那样工作。