AceInfinity
Emeritus, Contributor
So I wrote this in a console application, but basically it's a class that provides methods to multiply a matrix by a matrix. This is very useful for linear algebra and I am just starting to apply it to a project that uses a Jacobi rotation method for dealing with a matrix.
Code:
private static void TestMatrixMultiply()
{
MatrixTable matrix1 = new MatrixTable(
new int[5, 4]
{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20}
}
);
MatrixTable matrix2 = new MatrixTable(
new int[4, 5]
{
{ 1, 2, 3, 4, 5},
{ 6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
}
);
MatrixTable matrixResult = matrix1 * matrix2;
DisplayMatrix(matrixResult, "000");
}
private static void DisplayMatrix(MatrixTable table, string formatter)
{
Console.WriteLine(table.TableDimensions.ToString() + "\n");
for (int i = 0; i < table.Rows; i++)
{
List<int> data = new List<int>();
for (int j = 0; j < table.Columns; j++)
{
data.Add(table[i, j]);
}
Console.WriteLine(string.Join(" ", data.Select(k => k.ToString(formatter))));
}
}
public class MatrixTable
{
private int[,] _table;
public MatrixTable(Dimensions dimensions) : this(dimensions.Rows, dimensions.Columns) { }
public MatrixTable(int rows, int columns) : this(new int[rows, columns]) { }
public MatrixTable(int[,] table)
{
_table = table;
}
public int this[int row, int column]
{
get
{
return _table[row, column];
}
set
{
_table[row, column] = value;
}
}
public Dimensions TableDimensions
{
get
{
return new Dimensions(_table.GetLength(0), _table.GetLength(1));
}
}
public int Rows
{
get
{
return this.TableDimensions.Rows;
}
}
public int Columns
{
get
{
return this.TableDimensions.Columns;
}
}
private static Dimensions GetDestinationSize(MatrixTable table1, MatrixTable table2)
{
int rows;
if (table1.Rows > table2.Rows)
{
rows = table1.Rows;
}
else
{
rows = table2.Rows;
}
int columns;
if (table1.Columns > table2.Columns)
{
columns = table1.Columns;
}
else
{
columns = table2.Columns;
}
return new Dimensions(rows, columns);
}
public static MatrixTable operator *(MatrixTable table1, MatrixTable table2)
{
MatrixTable result = new MatrixTable(GetDestinationSize(table1, table2));
for (int i = 0; i < table1.Rows; i++)
{
for (int j = 0; j < table2.Columns; j++)
{
for (int k = 0; k < table1.Columns; k++)
{
result[i, j] += table1[i, k] * table2[k, j];
}
}
}
return result;
}
}
public struct Dimensions
{
public Dimensions(int rows, int columns)
{
_rows = rows;
_columns = columns;
}
private int _rows;
public int Rows
{
get
{
return _rows;
}
}
private int _columns;
public int Columns
{
get
{
return _columns;
}
}
public override string ToString()
{
return string.Format("Rows:{0}, Columns:{1}", this._rows, this._columns);
}
}