diff --git a/Startcode/matrix.c b/Startcode/matrix.c index 9f1c1cf..b238b81 100644 --- a/Startcode/matrix.c +++ b/Startcode/matrix.c @@ -4,29 +4,39 @@ // 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) { - MatrixType **storage = __builtin_malloc(rows * cols * sizeof(int)); - const Matrix matrix = {.rows = rows, .cols = cols, .storage = storage}; - - return matrix; + Matrix* m = malloc(sizeof(Matrix)); + m->rows = rows; + m->cols = cols; + m->storage = malloc(rows * cols * sizeof(MatrixType)); + return m; } void clearMatrix(Matrix *matrix) { - matrix->rows = 0; - matrix->cols = 0; - __builtin_free(matrix->storage); + for (int i = 0; i < matrix->rows; i++) + { + for (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[rowIdx][colIdx] = value; + matrix.storage[getMatrixIndex(matrix.cols, rowIdx, colIdx)] = value; } MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { - return matrix.storage[rowIdx][colIdx]; + return matrix.storage[getMatrixIndex(matrix->cols, rowIdx, colIdx)]; } Matrix add(const Matrix matrix1, const Matrix matrix2) @@ -42,7 +52,8 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) { for (unsigned int j = 0; j < matrix1.cols; j++) { - result.storage[i][j] = matrix1.storage[i][j] + matrix2.storage[i][j]; + unsigned int index = getMatrixIndex(matrix1.cols, i, j); + result.storage[index] = matrix1.storage[index] + matrix2.storage[index]; } } diff --git a/Startcode/matrix.h b/Startcode/matrix.h index ed29aae..8300fcb 100644 --- a/Startcode/matrix.h +++ b/Startcode/matrix.h @@ -6,11 +6,12 @@ typedef float MatrixType; // TODO Matrixtyp definieren +// Flat Storage: Nur ein Pointer, sorgt für zusammenhängendes array, kein verstreuter Speicher -> bessere Performance typedef struct { unsigned int rows; unsigned int cols; - MatrixType** storage; + MatrixType* storage; } Matrix; Matrix createMatrix(unsigned int rows, unsigned int cols);