diff --git a/Startcode/matrix.c b/Startcode/matrix.c index 4952d16..ea977a5 100644 --- a/Startcode/matrix.c +++ b/Startcode/matrix.c @@ -41,17 +41,82 @@ void clearMatrix(Matrix *matrix) void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { + // Sind Idx innerhalb der Matrix? + if (matrix.buffer != NULL && rowIdx < matrix.rows && colIdx < matrix.cols) + { + // Umrechnung von 2D auf 1D + matrix.buffer[rowIdx * matrix.cols + colIdx] = value; + } } MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { + // Sicherheitsprüfung wie beim setzen + if (matrix.buffer != NULL && rowIdx < matrix.rows && colIdx < matrix.cols) + { + return matrix.buffer[rowIdx * matrix.cols + colIdx]; + } + // Fehlerwert, falls außerhalb der grenzen + return UNDEFINED_MATRIX_VALUE; } Matrix add(const Matrix matrix1, const Matrix matrix2) { - + // Prüfen ob Zeilenanzahl gleich ist und ob buffer existieren + if (matrix1.buffer == NULL || matrix2.buffer == NULL || matrix1.rows != matrix2.rows) + { + return (Matrix){0}; + } + // Wenn beide Matrixen gleich groß sind: + if (matrix1.cols == matrix2.cols) + { + Matrix result = createMatrix(matrix1.rows, matrix1.cols); + if (result.buffer == NULL) return (Matrix){0}; + + unsigned int totalElements = matrix1.rows * matrix1.cols; + for (unsigned int i = 0; i < totalElements; i++) + { + result.buffer[i] = matrix1.buffer[i] + matrix2.buffer[i]; + } + return result; + } + //Wenn matrix2 ein Spaltenvektor ist + else if (matrix2.cols == 1) + { + Matrix result = createMatrix(matrix1.rows, matrix1.cols); + if (result.buffer == NULL) return (Matrix){0}; + + for (unsigned int r = 0; r < matrix1.rows; r++) + { + for (unsigned int c = 0; c < matrix1.cols; c++) + { + // Wert mit r und c aus m1 + Wert mit r aus m2 + result.buffer[r * matrix1.cols + c] = matrix1.buffer[r * matrix1.cols + c] + matrix2.buffer[r]; + } + } + return result; + } + //Wenn matrix1 ein Spaltenvektor ist + else if (matrix1.cols == 1) + { + Matrix result = createMatrix(matrix2.rows, matrix2.cols); + if (result.buffer == NULL) return (Matrix){0}; + + for (unsigned int r = 0; r < matrix2.rows; r++) + { + for (unsigned int c = 0; c < matrix2.cols; c++) + { + //gleich wie davor nur m1 und m2 getauscht + result.buffer[r * matrix2.cols + c] = matrix2.buffer[r * matrix2.cols + c] + matrix1.buffer[r]; + } + } + return result; + } + + return (Matrix){0}; + } Matrix multiply(const Matrix matrix1, const Matrix matrix2) @@ -86,7 +151,7 @@ Matrix multiply(const Matrix matrix1, const Matrix matrix2) matrix2.buffer[k * matrix2.cols + j]; } - // Berechneten Wert in der Ergebnismatrix speichern + // Berechneten Wert in der Ergebnismatrix speichern result.buffer[i * result.cols + j] = sum; } }