diff --git a/I2_NeuronalerAbsturz/Start_Mac/matrix.c b/I2_NeuronalerAbsturz/Start_Mac/matrix.c index ad00628..3f5b3a5 100644 --- a/I2_NeuronalerAbsturz/Start_Mac/matrix.c +++ b/I2_NeuronalerAbsturz/Start_Mac/matrix.c @@ -6,30 +6,112 @@ Matrix createMatrix(unsigned int rows, unsigned int cols) { + Matrix m; + + if (rows == 0 || cols == 0) + { + m.rows = 0; + m.cols = 0; + m.buffer = NULL; + return m; + } + + m.rows = rows; + m.cols = cols; + m.buffer = (MatrixType *)calloc(rows * cols, sizeof(MatrixType)); + return m; } void clearMatrix(Matrix *matrix) { - + if (matrix != NULL) + { + if (matrix->buffer != NULL) + { + free(matrix->buffer); + matrix->buffer = NULL; + } + + matrix->rows = 0; + matrix->cols = 0; + } } void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { - + if (matrix.buffer != NULL) + { + if (rowIdx < matrix.rows || colIdx < matrix.cols) + { + matrix.buffer[rowIdx * matrix.cols + colIdx] = value; + } + } } MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { - + if (matrix.buffer == NULL || rowIdx >= matrix.rows || colIdx >= matrix.cols) + { + return UNDEFINED_MATRIX_VALUE; + } + + return matrix.buffer[rowIdx * matrix.cols + colIdx]; } Matrix add(const Matrix matrix1, const Matrix matrix2) { - + Matrix result; + + if (matrix1.buffer == NULL || matrix2.buffer == NULL || matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols) + { + result.rows = 0; + result.cols = 0; + result.buffer = NULL; + return result; + } + + result = createMatrix(matrix1.rows, matrix1.cols); + + for (int i = 0; i < matrix1.rows; i++) + { + for (int j = 0; j < matrix1.cols; j++) + { + MatrixType value = getMatrixAt(matrix1, i, j) + getMatrixAt(matrix2, i, j); + setMatrixAt(value, result, i, j); + } + } + + return result; } Matrix multiply(const Matrix matrix1, const Matrix matrix2) { - -} \ No newline at end of file + Matrix result; + + if (matrix1.buffer == NULL || matrix2.buffer == NULL || matrix1.cols != matrix2.rows) + { + result.rows = 0; + result.cols = 0; + result.buffer = NULL; + return result; + } + + result = createMatrix(matrix1.rows, matrix2.cols); + + for (int i = 0; i < matrix1.rows; i++) + { + for (int j = 0; j < matrix2.cols; j++) + { + MatrixType sum = 0; + + for (int k = 0; k < matrix1.cols; k++) + { + sum += getMatrixAt(matrix1, i, k) * getMatrixAt(matrix2, k, j); + } + setMatrixAt(sum, result, i, j); + } + } + + return result; +} diff --git a/I2_NeuronalerAbsturz/Start_Mac/matrix.h b/I2_NeuronalerAbsturz/Start_Mac/matrix.h index cc640d1..3b9a3df 100644 --- a/I2_NeuronalerAbsturz/Start_Mac/matrix.h +++ b/I2_NeuronalerAbsturz/Start_Mac/matrix.h @@ -7,6 +7,13 @@ typedef float MatrixType; // TODO Matrixtyp definieren +typedef struct +{ + int rows; + int cols; + MatrixType *buffer; +} Matrix; + Matrix createMatrix(unsigned int rows, unsigned int cols); void clearMatrix(Matrix *matrix);