|
|
Arrays
TestMatMul.cs
using System;
class WrongDimensionException : ApplicationException {
}
class Test {
// multiply the matrices a and b; return the result
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;
}
// print the matrix a
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();
}
}
// create a matrix with the specified number of rows and colums;
// initialize it with consecutive numbers starting at startVal
static double[,] MakeMatrix(int rows, int cols, double startVal) {
double[,] a = new double[rows, cols];
for (int i = 0; i < rows; 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 = MatrixMult(a, b);
Print(c);
}
}
|
|