How to implement matrix multiplication in C#

2 Answers

0 votes
using System;

// Multiply rows of A by columns of B.

public class MatrixMultiplication
{
    static void Print(int[,] arr2d) {
        for (int i = 0; i < arr2d.GetLength(0); i++) {
            for (int j = 0; j < arr2d.GetLength(1); j++)
                Console.Write("{0,4}", arr2d[i, j]);
            Console.WriteLine();
        }
    }
    static int Calc(int[,] a, int[,] b, int i, int j) {
        int sum = 0;
        
        for (int x = 0; x < a.GetLength(0); x++) 
            sum += a[i, x] * b[x, j];
            
        return sum;
    }
    public static void Main(string[] args)
    {
        int[,] a = new int[3, 3] { { 1, 8, 5 }, { 6, 7, 1 }, { 8, 7, 6 } };
        int[,] b = new int[3, 3] { { 4, 8, 1 }, { 6, 5, 3 }, { 4, 6, 5 } };
        int[,] c = new int[a.GetLength(0), b.GetLength(1)];
 
        Print(a);
        Console.WriteLine();
        Print(b);
        Console.WriteLine();
 
        // c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])
 
        for (int i = 0; i < a.GetLength(0); i++)
            for (int j = 0; j < a.GetLength(1); j++)
                c[i, j] = Calc(a, b, i, j);
        Print(c);
    }
}



/*
run:
     
   1   8   5
   6   7   1
   8   7   6
 
   4   8   1
   6   5   3
   4   6   5
 
  72  78  50
  70  89  32
  98 135  59
 
*/


answered Jun 1, 2014 by avibootz
edited 3 days ago by avibootz
0 votes
using System;
 
// Multiply rows of A by columns of B.
 
public class MatrixMultiplication
{
    static void Print(int[,] arr2d) {
        for (int i = 0; i < arr2d.GetLength(0); i++) {
            for (int j = 0; j < arr2d.GetLength(1); j++)
                Console.Write("{0,4}", arr2d[i, j]);
            Console.WriteLine();
        }
    }
    static void multiple_matrix(int[,] a, int[,] b, int[,] c) {
        for (int i = 0; i < c.GetLength(0); i++) {
            for (int j = 0; j < c.GetLength(1); j++) {
                for (int k = 0; k < a.GetLength(1); k++) 
                    c[i, j] = c[i, j] + a[i, k] * b[k, j];
            }
        }
    }
    public static void Main(string[] args)
    {
        int[,] a = new int[3, 3] { { 1, 8, 5 }, { 6, 7, 1 }, { 8, 7, 6 } };
        int[,] b = new int[3, 3] { { 4, 8, 1 }, { 6, 5, 3 }, { 4, 6, 5 } };
        int[,] c = new int[a.GetLength(0), b.GetLength(1)];
  
        Print(a);
        Console.WriteLine();
        Print(b);
        Console.WriteLine();
  
        // c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])
         
        multiple_matrix(a, b, c);
        Print(c);
    }
}
 
 
 
/*
run:
      
   1   8   5
   6   7   1
   8   7   6
  
   4   8   1
   6   5   3
   4   6   5
  
  72  78  50
  70  89  32
  98 135  59
  
*/

 



answered Feb 28, 2016 by avibootz
edited 3 days ago by avibootz
...