Home   Cover Cover Cover Cover
 

Arrays

../../solutions/2/TestMatMul.cs
using System;

class WrongDimensionException : ApplicationException {
}

class Test {
  
  static double[,] MatrixMult(double[,] a, double[,] b) {
    if (a.GetLength(1) != b.GetLength(0))
      throw new WrongDimensionException();
    double[,] c = new double[a.GetLength(0), b.GetLength(1)];
    for (int i = 0; i < a.GetLength(0); i++) {
      for (int j = 0; j < b.GetLength(1); j++) {
        double sum = 0;
        for (int k = 0; k < a.GetLength(1); k++) {
          sum += a[i, k] * b[k, j];
        }
        c[i, j] = sum;
      }
    }
    return c;
  }
  
  static void Print(double[,] a) {
    for (int i = 0; i < a.GetLength(0); i++) {
      for (int j = 0; j < a.GetLength(1); j++) {
        Console.Write("{0, 7:f0}", a[i, j]);
      }
      Console.WriteLine();
    }
  }
  
  static double[,] MakeMatrix(int lines, int cols, double startVal) {
    double[,] a = new double[lines, cols];
    for (int i = 0; i < lines; i++)
      for (int j = 0; j < cols; j++)
        a[i, j] = startVal++;
    return a;
  }
  
  public static void Main() {
    double[,] a = MakeMatrix(10, 15, 1);
    double[,] b = MakeMatrix(15, 10, 100);
    double[,] c = null;
    long t = Environment.TickCount;
    for (int i = 1; i < 1000; i++) c = MatrixMult(a, b);
    t = Environment.TickCount - t;
    Console.WriteLine("t = " + t);
    Print(c);
  }
}