From 6d9aa3709a22c691e1c9a0125b7933b515de103b Mon Sep 17 00:00:00 2001 From: Markus Schreiber Date: Wed, 11 Nov 2026 07:12:26 +0100 Subject: [PATCH] Matrix Funktionen implementiert und getestet --- Startcode/matrix.c | 76 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 72 insertions(+), 4 deletions(-) diff --git a/Startcode/matrix.c b/Startcode/matrix.c index 0e4ce6e..33ae86d 100644 --- a/Startcode/matrix.c +++ b/Startcode/matrix.c @@ -44,24 +44,92 @@ void clearMatrix(Matrix *matrix) matrix->cols = 0; + } void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { - +if (matrix.buffer == NULL || + rowIdx >= matrix.rows || + colIdx >= matrix.cols) { + return; + } + 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) { - + + if (matrix1.rows != matrix2.rows || + (matrix1.cols != matrix2.cols && + matrix1.cols != 1 && + matrix2.cols != 1)) { + return createMatrix(0, 0); + } + + // Ungültige Eingabematrizen abfangen + if (matrix1.buffer == NULL || matrix2.buffer == NULL) { + return createMatrix(0, 0); + } + + // Größere Spaltenanzahl bestimmen + unsigned int cols = matrix1.cols > matrix2.cols + ? matrix1.cols : matrix2.cols; + + Matrix result = createMatrix(matrix1.rows, cols); + + if (result.buffer == NULL) { + return result; + } + + for (unsigned int i = 0; i < result.rows; i++) { + for (unsigned int j = 0; j < result.cols; j++) { + + // Bei einer Spalte immer Spalte 0 verwenden + unsigned int j1 = matrix1.cols == 1 ? 0 : j; + unsigned int j2 = matrix2.cols == 1 ? 0 : j; + + result.buffer[i * result.cols + j] = + matrix1.buffer[i * matrix1.cols + j1] + + matrix2.buffer[i * matrix2.cols + j2]; + } + } + + return result; + } Matrix multiply(const Matrix matrix1, const Matrix matrix2) { - +if (matrix1.cols != matrix2.rows) { + return createMatrix(0, 0); + } + + // Ergebnismatrix erstellen + Matrix result = createMatrix(matrix1.rows, matrix2.cols); + + // Matrizen multiplizieren + for (unsigned int rowIdx = 0; rowIdx < matrix1.rows; rowIdx++) { + for (unsigned int colIdx = 0; colIdx < matrix2.cols; colIdx++) { + for (unsigned int k = 0; k < matrix1.cols; k++) { + result.buffer[rowIdx * result.cols + colIdx] += + matrix1.buffer[rowIdx * matrix1.cols + k] * + matrix2.buffer[k * matrix2.cols + colIdx]; +} +} +} +return result; } \ No newline at end of file