Add Matrices
This algorithm computes the sum of two matrices.
/*****Please include following header files*****/
// cstdlib
/***********************************************/
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 AddMatrices(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] = 1;
m1[0][1] = 2;
m1[1][0] = 3;
m1[1][1] = 4;
int** m2 = CreateMatrix(2, 2);
m2[0][0] = 5;
m2[0][1] = 6;
m2[1][0] = 2;
m2[1][1] = 1;
Matrix matrix1 = { m1, 2, 2 };
Matrix matrix2 = { m2, 2, 2 };
Matrix sumMatrix = AddMatrices(matrix1, matrix2);
Output
[0][0] = 6
[0][1] = 8
[1][0] = 5
[1][1] = 5