#include #include "matrix.h" /* * Erstellt eine Matrix. Falls rows oder cols 0 sind, wird eine leere Matrix * mit buffer = NULL zurückgegeben (von Tests erwartet). */ Matrix createMatrix(unsigned int rows, unsigned int cols) { Matrix m; // Tests erwarten: Wenn eine Dimension 0 ist -> komplett leere Matrix if (rows == 0 || cols == 0) { m.rows = 0; m.cols = 0; m.buffer = NULL; return m; } m.rows = rows; m.cols = cols; m.buffer = malloc(rows * cols * sizeof(MatrixType)); if (m.buffer == NULL) { m.rows = 0; m.cols = 0; return m; } for (unsigned int i = 0; i < rows * cols; i++) { m.buffer[i] = UNDEFINED_MATRIX_VALUE; } return m; } /* * Gibt den Speicher der Matrix frei und setzt alle Felder wie von Tests erwartet. */ void clearMatrix(Matrix *matrix) { if (matrix->buffer != NULL) { free(matrix->buffer); } matrix->buffer = NULL; matrix->rows = 0; matrix->cols = 0; } /* * Setzt einen Wert an Position (rowIdx, colIdx). */ void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { if (matrix.buffer == NULL) return; if (rowIdx >= matrix.rows || colIdx >= matrix.cols) return; matrix.buffer[rowIdx * matrix.cols + colIdx] = value; } /* * Gibt einen Wert zurück oder UNDEFINED_MATRIX_VALUE bei ungültigen Indizes. */ MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { if (matrix.buffer == NULL) return UNDEFINED_MATRIX_VALUE; if (rowIdx >= matrix.rows || colIdx >= matrix.cols) return UNDEFINED_MATRIX_VALUE; return matrix.buffer[rowIdx * matrix.cols + colIdx]; } /* * Addiert zwei Matrizen gleicher Dimension. * Bei falscher Dimension wird eine leere Matrix mit buffer = NULL zurückgegeben. */ Matrix add(const Matrix matrix1, const Matrix matrix2) { if (matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols) { Matrix empty = {0, 0, NULL}; return empty; } Matrix result = createMatrix(matrix1.rows, matrix1.cols); for (unsigned int r = 0; r < matrix1.rows; r++) { for (unsigned int c = 0; c < matrix1.cols; c++) { MatrixType value = getMatrixAt(matrix1, r, c) + getMatrixAt(matrix2, r, c); setMatrixAt(value, result, r, c); } } return result; } /* * Multipliziert zwei Matrizen. */ Matrix multiply(const Matrix matrix1, const Matrix matrix2) { if (matrix1.cols != matrix2.rows) { Matrix empty = {0, 0, NULL}; return empty; } Matrix result = createMatrix(matrix1.rows, matrix2.cols); for (unsigned int r = 0; r < matrix1.rows; r++) { for (unsigned int c = 0; c < matrix2.cols; c++) { MatrixType sum = 0; for (unsigned int k = 0; k < matrix1.cols; k++) { sum += getMatrixAt(matrix1, r, k) * getMatrixAt(matrix2, k, c); } setMatrixAt(sum, result, r, c); } } return result; }