From 3299cd29e360a844967ef370986f1c223a52ee3b Mon Sep 17 00:00:00 2001 From: Simon Schuerer Date: Mon, 10 Nov 2025 08:14:02 +0000 Subject: [PATCH] matrix.c aktualisiert --- matrix.c | 64 +++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/matrix.c b/matrix.c index ad00628..90297b5 100644 --- a/matrix.c +++ b/matrix.c @@ -4,32 +4,72 @@ // TODO Matrix-Funktionen implementieren -Matrix createMatrix(unsigned int rows, unsigned int cols) +MatrixTyp erstelleMatrix(unsigned int reihen, unsigned int spalten) { - + MatrixTyp m; + m.reihen = reihen; + m.spalten = spalten; + m.werte = (MatrixWert *)malloc(reihen * spalten * sizeof(MatrixWert)); + for (unsigned int i = 0; i < reihen * spalten; ++i) { + m.werte[i] = UNDEFINIERTER_MATRIXWERT; + } + return m; } -void clearMatrix(Matrix *matrix) +void loescheMatrix(MatrixTyp *matrix) { - + free(matrix->werte); + matrix->werte = NULL; + matrix->reihen = 0; + matrix->spalten = 0; } -void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) +void setzeMatrixWert(MatrixWert wert, MatrixTyp matrix, unsigned int reiheIndex, unsigned int spalteIndex) { - + if (reiheIndex < matrix.reihen && spalteIndex < matrix.spalten) { + matrix.werte[reiheIndex * matrix.spalten + spalteIndex] = wert; + } } -MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) +MatrixWert holeMatrixWert(const MatrixTyp matrix, unsigned int reiheIndex, unsigned int spalteIndex) { - + if (reiheIndex < matrix.reihen && spalteIndex < matrix.spalten) { + return matrix.werte[reiheIndex * matrix.spalten + spalteIndex]; + } + return UNDEFINIERTER_MATRIXWERT; } -Matrix add(const Matrix matrix1, const Matrix matrix2) +MatrixTyp addiereMatrix(const MatrixTyp matrix1, const MatrixTyp matrix2) { - + if (matrix1.reihen != matrix2.reihen || matrix1.spalten != matrix2.spalten) { + return erstelleMatrix(0, 0); + } + + MatrixTyp ergebnis = erstelleMatrix(matrix1.reihen, matrix1.spalten); + for (unsigned int i = 0; i < matrix1.reihen; ++i) { + for (unsigned int j = 0; j < matrix1.spalten; ++j) { + MatrixWert wert = holeMatrixWert(matrix1, i, j) + holeMatrixWert(matrix2, i, j); + setzeMatrixWert(wert, ergebnis, i, j); + } + } + return ergebnis; } -Matrix multiply(const Matrix matrix1, const Matrix matrix2) +MatrixTyp multipliziereMatrix(const MatrixTyp matrix1, const MatrixTyp matrix2) { - + if (matrix1.spalten != matrix2.reihen) { + return erstelleMatrix(0, 0); + } + + MatrixTyp ergebnis = erstelleMatrix(matrix1.reihen, matrix2.spalten); + for (unsigned int i = 0; i < matrix1.reihen; ++i) { + for (unsigned int j = 0; j < matrix2.spalten; ++j) { + MatrixWert summe = 0; + for (unsigned int k = 0; k < matrix1.spalten; ++k) { + summe += holeMatrixWert(matrix1, i, k) * holeMatrixWert(matrix2, k, j); + } + setzeMatrixWert(summe, ergebnis, i, j); + } + } + return ergebnis; } \ No newline at end of file