How to transpose matrix?

会有一股神秘感。 提交于 2019-12-01 04:09:18
public double[,] Transpose(double[,] matrix)
{
    int w = matrix.GetLength(0);
    int h = matrix.GetLength(1);

    double[,] result = new double[h, w];

    for (int i = 0; i < w; i++)
    {
        for (int j = 0; j < h; j++)
        {
            result[j, i] = matrix[i, j];
        }
    }

    return result;
}
public class Matrix<T>
{
    public static T[,] TransposeMatrix(T[,] matrix)
    {
        var rows    = matrix.GetLength(0);
        var columns = matrix.GetLength(1);

        var result = new T[columns, rows];

        for (var c = 0; c < columns; c++)
        {
            for (var r = 0; r < rows; r++)
            {
                result[c, r] = matrix[r, c];
            }
        }

        return result;
    }
}

And that is how to call it:

int[,] matris = 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},

        };
var tMatrix = Matrix<int>.TransposeMatrix(matris);

Transpose of Matrix in c#. Instead of printing result, you can save them in another matrix. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!