diff --git a/matrix.c b/matrix.c index 8da5a94..55d3dd5 100644 --- a/matrix.c +++ b/matrix.c @@ -40,20 +40,74 @@ void clearMatrix(Matrix *matrix) void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { - + if (rowIdx >= matrix.rows || colIdx >= matrix.cols) { + fprintf(stderr, "Error: setMatrixAt index out of bounds.\n"); + return; + } + + matrix.buffer[rowIdx * matrix.cols + colIdx] = value; } MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { - + if (rowIdx >= matrix.rows || colIdx >= matrix.cols) { + fprintf(stderr, "Error: getMatrixAt index out of bounds.\n"); + return UNDEFINED_MATRIX_VALUE; + } + + return matrix.buffer[rowIdx * matrix.cols + colIdx]; } Matrix add(const Matrix matrix1, const Matrix matrix2) { - + if (matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols) { + fprintf(stderr, "Error: Matrix dimensions do not match for addition.\n"); + Matrix empty = {0, 0, NULL}; + return empty; + } + + Matrix result = createMatrix(matrix1.rows, matrix1.cols); + if (result.buffer == NULL) { + return result; + } + + for (unsigned int i = 0; i < matrix1.rows; i++) { + for (unsigned int j = 0; j < matrix1.cols; j++) { + setMatrixAt( + getMatrixAt(matrix1, i, j) + getMatrixAt(matrix2, i, j), + result, + i, j + ); + } + } + + return result; } Matrix multiply(const Matrix matrix1, const Matrix matrix2) { - + if (matrix1.cols != matrix2.rows) { + fprintf(stderr, "Error: Invalid matrix dimensions for multiplication.\n"); + Matrix empty = {0, 0, NULL}; + return empty; + } + + Matrix result = createMatrix(matrix1.rows, matrix2.cols); + if (result.buffer == NULL) { + return result; + } + + for (unsigned int i = 0; i < matrix1.rows; i++) { + for (unsigned int j = 0; j < matrix2.cols; j++) { + MatrixType sum = 0.0f; + + for (unsigned int k = 0; k < matrix1.cols; k++) { + sum += getMatrixAt(matrix1, i, k) * getMatrixAt(matrix2, k, j); + } + + setMatrixAt(sum, result, i, j); + } + } + + return result; } \ No newline at end of file diff --git a/neuralNetwork.c b/neuralNetwork.c index bd8f164..1e9dce8 100644 --- a/neuralNetwork.c +++ b/neuralNetwork.c @@ -170,7 +170,7 @@ NeuralNetwork loadModel(const char *path) static Matrix imageBatchToMatrixOfImageVectors(const GrayScaleImage images[], unsigned int count) { - Matrix matrix = {NULL, 0, 0}; + Matrix matrix = {NULL, 0, 0}; //hier evtl Null auf int casten? if(count > 0 && images != NULL) {