#include #include #include "matrix.h" // TODO Matrix-Funktionen implementieren int getMatrixIndex(unsigned int cols, unsigned int rowIdx, unsigned int colIdx) { return rowIdx * cols + colIdx; } Matrix createMatrix(unsigned int rows, unsigned int cols) { Matrix* m = malloc(sizeof(Matrix)); m->rows = rows; m->cols = cols; m->storage = malloc(rows * cols * sizeof(MatrixType)); return m; } void clearMatrix(Matrix *matrix) { for (unsigned int i = 0; i < matrix->rows; i++) { for (unsigned int j = 0; j < matrix->cols; j++) { setMatrixElement(matrix, i, j, UNDEFINED_MATRIX_VALUE); } } } void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { matrix.storage[getMatrixIndex(matrix.cols, rowIdx, colIdx)] = value; } MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { return matrix.storage[getMatrixIndex(matrix.cols, rowIdx, colIdx)]; } Matrix add(const Matrix matrix1, const Matrix matrix2) { if (matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols) { fprintf(stderr, "Fehler: Dimensionen stimmen nicht überein (%ux%u und %ux%u)\n", matrix1.rows, matrix1.cols, matrix2.rows, matrix2.cols); return (Matrix){ .rows = 0, .cols = 0, .storage = NULL }; } Matrix result = createMatrix(matrix1.rows, matrix1.cols); // check, ob genügend Speicher vorhanden if (result.storage == NULL) { return (Matrix){ .rows = 0, .cols = 0, .storage = NULL }; } for (unsigned int i = 0; i < matrix1.rows; i++) { for (unsigned int j = 0; j < matrix1.cols; j++) { unsigned int index = getMatrixIndex(matrix1.cols, i, j); result.storage[index] = matrix1.storage[index] + matrix2.storage[index]; } } return result; } Matrix multiply(const Matrix matrix1, const Matrix matrix2) { if (matrix1.cols != matrix2.rows) { fprintf(stderr, "Fehler: Spalten von Matrix 1 (%u) entsprechen nicht Zeilen von Matrix 2 (%u)\n", matrix1.cols, matrix2.rows); return (Matrix){ .rows = 0, .cols = 0, .storage = NULL }; } Matrix result = createMatrix(matrix1.rows, matrix2.cols); // check, ob genügend Speicher vorhanden if (result.storage == NULL) { return (Matrix){ .rows = 0, .cols = 0, .storage = NULL }; } for (unsigned int i = 0; i < matrix1.rows; i++) { for (unsigned int j = 0; j < matrix2.cols; j++) { MatrixType sum = 0; for (unsigned int k = 0; k < matrix1.cols; k++) { MatrixType val1 = matrix1.storage[i * matrix1.cols + k]; MatrixType val2 = matrix2.storage[k * matrix2.cols + j]; sum += val1 * val2; } result.storage[i * result.cols + j] = sum; } } return result; }