Add Matrices
This algorithm computes the sum of two 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 AddMatrices(Matrix firstMatrix, Matrix secondMatrix)
{
if (firstMatrix.Rows == secondMatrix.Rows && firstMatrix.Columns == secondMatrix.Columns)
{
int[,] sum = new int[firstMatrix.Rows, firstMatrix.Columns];
for (int i = 0; i < firstMatrix.Rows; ++i)
{
for (int j = 0; j < firstMatrix.Columns; ++j)
{
sum[i, j] = firstMatrix._Matrix[i, j] + secondMatrix._Matrix[i, j];
}
}
return new Matrix(sum, firstMatrix.Rows, firstMatrix.Columns);
}
return default(Matrix);
}
Example
int[,] m1 = new int[2, 2];
m1[0, 0] = 1;
m1[0, 1] = 2;
m1[1, 0] = 3;
m1[1, 1] = 4;
int[,] m2 = new int[2, 2];
m2[0, 0] = 5;
m2[0, 1] = 6;
m2[1, 0] = 2;
m2[1, 1] = 1;
Matrix matrix1 = new Matrix(m1, 2, 2);
Matrix matrix2 = new Matrix(m2, 2, 2);
Matrix sumMatrix = AddMatrices(matrix1, matrix2);
Output
[0, 0] = 6
[0, 1] = 8
[1, 0] = 5
[1, 1] = 5