Subtract Matrices
This algorithm finds difference between corresponding elements 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 SubtractMatrices(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] = 8;
m1[0, 1] = 6;
m1[1, 0] = 7;
m1[1, 1] = 5;
int[,] m2 = new int[2, 2];
m2[0, 0] = 4;
m2[0, 1] = 3;
m2[1, 0] = 5;
m2[1, 1] = 2;
Matrix matrix1 = new Matrix(m1, 2, 2);
Matrix matrix2 = new Matrix(m2, 2, 2);
Matrix sumMatrix = SubtractMatrices(matrix1, matrix2);
Output
[0, 0] = 4
[0, 1] = 3
[1, 0] = 2
[1, 1] = 3