Multiply Matrices
This algorithm multiplies two given 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 MultiplyMatrices(Matrix firstMatrix, Matrix secondMatrix) {
int** mult = CreateMatrix(firstMatrix.Rows, secondMatrix.Columns);
if (firstMatrix.Columns != secondMatrix.Rows)
return{ NULL, 0, 0 };
for (int i = 0; i < firstMatrix.Rows; ++i)
for (int j = 0; j < secondMatrix.Columns; ++j)
{
mult[i][j] = 0;
}
for (int i = 0; i < firstMatrix.Rows; ++i)
for (int j = 0; j < secondMatrix.Columns; ++j)
for (int k = 0; k < firstMatrix.Columns; ++k)
{
mult[i][j] += firstMatrix.Matrix[i][k] * secondMatrix.Matrix[k][j];
}
return{ mult, firstMatrix.Rows, secondMatrix.Columns };
}
Example
int** m1 = CreateMatrix(2, 3);
m1[0][0] = 3;
m1[0][1] = -2;
m1[0][2] = 5;
m1[1][0] = 3;
m1[1][1] = 0;
m1[1][2] = 4;
int** m2 = CreateMatrix(3, 2);
m2[0][0] = 2;
m2[0][1] = 3;
m2[1][0] = -9;
m2[1][1] = 0;
m2[2][0] = 0;
m2[2][1] = 4;
Matrix matrix1 = { m1, 2, 3 };
Matrix matrix2 = { m2, 3, 2 };
Matrix sumMatrix = MultiplyMatrices(matrix1, matrix2);
Output
[0][0] = 24
[0][1] = 29
[1][0] = 6
[1][1] = 25