打印矩阵及其转置,C#

时间:2013-08-25 17:27:40

标签: c# algorithm matrix transpose

我有一个程序可以创建一个转置5x8矩阵。我创建了一个多维5x8数组,我还创建了一个新的数组,用于保存多维数组的转置。问题是,我首先想要将原始矩阵写出到控制台,并且在同一行上我希望将转置写出来。这是我的代码:

 class Program
{
    static void Main(string[] args)
    {


        int[,] matrix = new int[5, 8] { 
       { 1, 2, 3, 4, 5,6,7,8 }, 
       { 9,10,11,12,13,14,15,16},
       { 17,18,19,20,21,22,23,24 },
       { 25,26,27,28,29,30,31,32 },
       { 33,34,35,36,37,38,39,40 },

        };

        for (int j = 0; j < 8; j++)
        {
            for (int r = 0; r < 5; r++)
                Console.Write("{0} ", matrix[r, j]);

            Console.WriteLine();
        }

        int[,] newArray = new int[8, 5];
        for (int j = 0; j < 8; j++)
            for (int r = 0; r < 5; r++)
                newArray[j, r] = matrix[r, j];




        Console.ReadLine();

    }
}

我想要的是在控制台窗口显示如下: http://pbrd.co/19SXR0J

但我只能打印转置矩阵。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

计算转置后,您可以同时打印两行。

 for (int j = 0; j < 8; j++)
    {
        //write a line from the first matrix
        for (int r = 0; r < 5; r++)
            Console.Write("{0} ", matrix[r, j]);

        //add some spaces for visual separation
        Console.Write("\t\t");

        //write a line from the transpose matrix
        for (int r = 0; r < 5; r++)
            Console.Write("{0} ", newArray[r, j]);

        Console.WriteLine();
    }