#include #include #include "matrix.h" // TODO Matrix-Funktionen implementieren Matrix createMatrix(unsigned int rows, unsigned int cols) { Matrix matrix; // Prüfen, ob eine Dimension 0 ist if (rows == 0 || cols == 0) { matrix.rows = 0; matrix.cols = 0; matrix.buffer = NULL; return matrix; } // Zeilen und Spalten festlegen matrix.rows = rows; matrix.cols = cols; // Speicher reservieren matrix.buffer = calloc(rows * cols, sizeof(MatrixType)); //Prüfen ob die Speichereservierung fehlgeschlagen ist if (matrix.buffer == NULL) { matrix.rows = 0; matrix.cols = 0; } return matrix; } void clearMatrix(Matrix *matrix) { free(matrix->buffer); matrix->buffer = NULL; matrix->rows = 0; 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; }