Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my Matrix code..i am multiplying two matrix. one of matrix is scalar(means digonal elemnts r same..)but when i run this code Getting wrong answer...
C#
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();

        }
Posted
Updated 14-Feb-12 23:02pm
v2

1 solution

The formula you are using is wrong, change
C#
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();
            }


to
C#
for (int i = 0; i < 3; i++)
{
  for (int j = 0; j < 3; j++)
  {
    for (int k = 0; k < 3; k++)
    {
       result[i, j] = result[i, j] + matrix1[i, k] * matrix2[k, j];
    }
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900