Subtract Matrices
This algorithm finds difference between corresponding elements of two matrices.
/*****Please include following header files*****/
// stdlib.h
/***********************************************/
typedef struct {
int** Matrix;
int Rows;
int Columns;
} Matrix;
int** CreateMatrix(int rowCount, int colCount) {
int** matrix = (int**)malloc(sizeof(int*) * rowCount);
for (int i = 0; i < rowCount; ++i) {
matrix[i] = (int*)malloc(sizeof(int) * colCount);
}
return matrix;
}
Matrix SubtractMatrices(Matrix firstMatrix, Matrix secondMatrix) {
if (firstMatrix.Rows == secondMatrix.Rows && firstMatrix.Columns == secondMatrix.Columns) {
int** sum = CreateMatrix(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{ sum, firstMatrix.Rows, firstMatrix.Columns };
}
return{ NULL, 0, 0 };
}
Example
int** m1 = CreateMatrix(2, 2);
m1[0][0] = 8;
m1[0][1] = 6;
m1[1][0] = 7;
m1[1][1] = 5;
int** m2 = CreateMatrix(2, 2);
m2[0][0] = 4;
m2[0][1] = 3;
m2[1][0] = 5;
m2[1][1] = 2;
Matrix matrix1 = { m1, 2, 2 };
Matrix matrix2 = { m2, 2, 2 };
Matrix sumMatrix = SubtractMatrices(matrix1, matrix2);
Output
[0][0] = 4
[0][1] = 3
[1][0] = 2
[1][1] = 3