Multiply Matrices
This algorithm multiplies two given matrices
public struct Matrix
{
public int[,] _Matrix;
public int Rows;
public int Columns;
public Matrix(int[,] matrix, int rows, int columns)
{
this._Matrix = matrix;
this.Rows = rows;
this.Columns = columns;
}
}
public static Matrix MultiplyMatrices(Matrix firstMatrix, Matrix secondMatrix)
{
int[,] mult = new int[firstMatrix.Rows, secondMatrix.Columns];
if (firstMatrix.Columns != secondMatrix.Rows)
return default(Matrix);
for (int i = 0; i < firstMatrix.Rows; ++i)
for (int j = 0; j < secondMatrix.Columns; ++j)
{
mult[i, j] = 0;
}
for (int i = 0; i < firstMatrix.Rows; ++i)
for (int j = 0; j < secondMatrix.Columns; ++j)
for (int k = 0; k < firstMatrix.Columns; ++k)
{
mult[i, j] += firstMatrix._Matrix[i, k] * secondMatrix._Matrix[k, j];
}
return new Matrix(mult, firstMatrix.Rows, secondMatrix.Columns);
}
Example
int[,] m1 = new int[2, 3];
m1[0, 0] = 3;
m1[0, 1] = -2;
m1[0, 2] = 5;
m1[1, 0] = 3;
m1[1, 1] = 0;
m1[1, 2] = 4;
int[,] m2 = new int[3, 2];
m2[0, 0] = 2;
m2[0, 1] = 3;
m2[1, 0] = -9;
m2[1, 1] = 0;
m2[2, 0] = 0;
m2[2, 1] = 4;
Matrix matrix1 = new Matrix(m1, 2, 3);
Matrix matrix2 = new Matrix(m2, 3, 2);
Matrix sumMatrix = MultiplyMatrices(matrix1, matrix2);
Output
[0, 0] = 24
[0, 1] = 29
[1, 0] = 6
[1, 1] = 25