forked from freudenreichan/info2Praktikum-NeuronalesNetz
feat: multiply method
This commit is contained in:
1 parent
5e1a1fdf72
commit
3519fc9af6
1 file changed
+42
-4
+42
-4
@@ -20,9 +20,9 @@ Matrix createMatrix(unsigned int rows, unsigned int cols)
|
||||
|
||||
void clearMatrix(Matrix *matrix)
|
||||
{
|
||||
for (int i = 0; i < matrix->rows; i++)
|
||||
for (unsigned int i = 0; i < matrix->rows; i++)
|
||||
{
|
||||
for (int j = 0; j < matrix->cols; j++)
|
||||
for (unsigned int j = 0; j < matrix->cols; j++)
|
||||
{
|
||||
setMatrixElement(matrix, i, j, UNDEFINED_MATRIX_VALUE);
|
||||
}
|
||||
@@ -43,11 +43,18 @@ Matrix add(const Matrix matrix1, const Matrix matrix2)
|
||||
{
|
||||
if (matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols)
|
||||
{
|
||||
return matrix1;
|
||||
fprintf(stderr, "Fehler: Dimensionen stimmen nicht überein (%ux%u und %ux%u)\n",
|
||||
matrix1->rows, matrix1->cols, matrix2->rows, matrix2->cols);
|
||||
return (Matrix){ .rows = 0, .cols = 0, .storage = NULL };
|
||||
}
|
||||
|
||||
Matrix result = createMatrix(matrix1.rows, matrix1.cols);
|
||||
|
||||
// check, ob genügend Speicher vorhanden
|
||||
if (result.storage == NULL) {
|
||||
return (Matrix){ .rows = 0, .cols = 0, .storage = NULL };
|
||||
}
|
||||
|
||||
for (unsigned int i = 0; i < matrix1.rows; i++)
|
||||
{
|
||||
for (unsigned int j = 0; j < matrix1.cols; j++)
|
||||
@@ -62,5 +69,36 @@ Matrix add(const Matrix matrix1, const Matrix matrix2)
|
||||
|
||||
Matrix multiply(const Matrix matrix1, const Matrix matrix2)
|
||||
{
|
||||
|
||||
if (matrix1.cols != matrix2.rows)
|
||||
{
|
||||
fprintf(stderr, "Fehler: Spalten von Matrix 1 (%u) entsprechen nicht Zeilen von Matrix 2 (%u)\n",
|
||||
matrix1.cols, matrix2.rows);
|
||||
return (Matrix){ .rows = 0, .cols = 0, .storage = NULL };
|
||||
}
|
||||
|
||||
Matrix result = createMatrix(matrix1.rows, matrix2.cols);
|
||||
|
||||
// check, ob genügend Speicher vorhanden
|
||||
if (result.storage == NULL) {
|
||||
return (Matrix){ .rows = 0, .cols = 0, .storage = NULL };
|
||||
}
|
||||
|
||||
for (unsigned int i = 0; i < matrix1.rows; i++)
|
||||
{
|
||||
for (unsigned int j = 0; j < matrix2.cols; j++)
|
||||
{
|
||||
MatrixType sum = 0;
|
||||
|
||||
for (unsigned int k = 0; k < matrix1.cols; k++)
|
||||
{
|
||||
MatrixType val1 = matrix1.storage[i * matrix1.cols + k];
|
||||
MatrixType val2 = matrix2.storage[k * matrix2.cols + j];
|
||||
sum += val1 * val2;
|
||||
}
|
||||
|
||||
result.storage[i * result.cols + j] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
Reference in new issue
Block a user