How to transpose matrix?

半腔热情 提交于 2019-12-04 00:51:59

问题


I have made 8x8 matrix using c#, and now I need to transpose the matrix. Can you help me to transpose the matrix? This is my matrix

public double[,] MatriksT(int blok)
{
    double[,] matrixT = new double[blok, blok];

    for (int j = 0; j < blok ; j++)
    {
        matrixT[0, j] = Math.Sqrt(1 / (double)blok);

    }

    for (int i = 1; i < blok; i++)
    {
        for (int j = 0; j < blok; j++)
        {
            matrixT[i, j] = Math.Sqrt(2 / (double)blok) * Math.Cos(((2 * j + 1) * i * Math.PI) / 2 * blok);
        }
    }

    return matrixT;

}

回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/29483660/how-to-transpose-matrix

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