How to multiply a matrix in C#?

流过昼夜 提交于 2019-11-29 11:55:51
ja72

Read this MSDN Magazine article by James McCaffrey and use the code below as an extension method. They use a jagged array which is more convenient and sometimes faster than a 2D array. Change any data[i][j] to data[i,j] to make the code work with a 2D array.

public static double[] MatrixProduct(this double[][] matrixA,
    double[] vectorB)
{
    int aRows=matrixA.Length; int aCols=matrixA[0].Length;
    int bRows=vectorB.Length;
    if (aCols!=bRows)
        throw new Exception("Non-conformable matrices in MatrixProduct");
    double[] result=new double[aRows];
    for (int i=0; i<aRows; ++i) // each row of A
        for (int k=0; k<aCols; ++k)
            result[i]+=matrixA[i][k]*vectorB[k];
    return result;
}
public static double[][] MatrixProduct(this double[][] matrixA,
    double[][] matrixB)
{
    int aRows=matrixA.Length; int aCols=matrixA[0].Length;
    int bRows=matrixB.Length; int bCols=matrixB[0].Length;
    if (aCols!=bRows)
        throw new Exception("Non-conformable matrices in MatrixProduct");
    double[][] result=MatrixCreate(aRows, bCols);
    for (int i=0; i<aRows; ++i) // each row of A
        for (int j=0; j<bCols; ++j) // each col of B
            for (int k=0; k<aCols; ++k)
                result[i][j]+=matrixA[i][k]*matrixB[k][j];
    return result;
}
public static double[][] MatrixCreate(int rows, int cols)
{
    // creates a matrix initialized to all 0.0s  
    // do error checking here?  
    double[][] result=new double[rows][];
    for (int i=0; i<rows; ++i)
        result[i]=new double[cols];
    // auto init to 0.0  
    return result;
}

This is the modified version of my method, as far as I've been testing this approach works fine.

    public void multiplicarPor(Matriz m)
    {
        if (this.estructura.GetLength(1) == m.estructura.GetLength(0))
        {
            Matriz resultante = new Matriz(this.estructura.GetLength(0), m.estructura.GetLength(1));
            for (int i = 0; i < this.estructura.GetLength(0); i++)
            {
                for (int j = 0; j < m.estructura.GetLength(1); j++)
                {
                    resultante.estructura[i, j] = 0;
                    for (int z = 0; z < this.estructura.GetLength(1); z++)
                    {
                        resultante.estructura[i, j] += this.estructura[i, z] * m.estructura[z, j];
                    }
                }
            }
            this.estructura = resultante.estructura;
        }
        else
        {
            Console.WriteLine("No se pueden multiplicar estas matrices");
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!