乘以两个矩阵但得到错误的答案

时间:2012-02-15 09:52:30

标签: c# matrix

这是我的矩阵代码。我乘以两个矩阵。其中一个矩阵是标量(意思是对角元素是相同的),但是当我运行这个代码时,我得到了错误的答案。

static void Main(string[] args)
{
    int[,] matrix1 = new int[3, 3];
    int[,] matrix2 = new int[3, 3];
    int[,] result = new int[3, 3];

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            Console.WriteLine("Enter 1st Matrix: ");
            matrix1[i, j] = Convert.ToInt32(Console.ReadLine());
        }
    }

    Console.ReadLine();

    for (int k = 0; k < 3; k++)
    {
        for (int l = 0; l < 3; l++)
        {
            Console.WriteLine("Enter 2nd Matrix: ");
            matrix2[k, l] = Convert.ToInt32(Console.ReadLine());
        }
    }

    Console.WriteLine();
    Console.WriteLine("Matrix 1: ");

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            Console.Write(matrix1[i, j] + " ");
        }
        Console.WriteLine();
    }

    Console.WriteLine();
    Console.WriteLine("Matrix 2: ");

    for (int k = 0; k < 3; k++)
    {
        for (int l = 0; l < 3; l++)
        {
            Console.Write(matrix2[k, l] + " ");
        }
        Console.WriteLine();
    }

    Console.WriteLine("Matrix 1 * Matrix 2: ");

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            result[i, j] = result[i, j] + matrix1[i, j] * matrix2[i, j];
            Console.Write(result[i, j] + " ");
        }
        Console.WriteLine();
    }

    Console.ReadLine();
    Console.ReadLine();
}

1 个答案:

答案 0 :(得分:4)

你没有将矩阵相乘,而是将它们的值相乘。见https://en.wikipedia.org/wiki/Matrix_multiplication

E.g。 {{1, 1}, {0, 0}} x {{1, 0}, {1, 0}}应生成{{2, 0}, {0, 0}},而不是{{1, 0}, {0, 0}}

这是矩阵乘法的正确代码(注意它的复杂度为O(n ^ 3),而不是O(n ^ 2)):

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                result[i, j] = 0;
                for(int k = 0; k < 3; k++)
                {
                    result[i, j] = result[i, j] + matrix1[i, k] * matrix2[k, j];
                }
                Console.Write(result[i, j] + " ");
            }
            Console.WriteLine();
        }