#include #include #include "matrix.h" // TODO Matrix-Funktionen implementieren Matrix createMatrix(unsigned int rows, unsigned int cols) { Matrix matrix; matrix.rows = rows; matrix.cols = cols; if(matrix.rows == 0 || matrix.cols == 0){ // prüfen, ob ungültige Dimensionen übergeben wurden, wenn ja, "error matrix" erstellen matrix.rows = 0; matrix.cols = 0; matrix.buffer = NULL; } else { // für gültige Dimensionen: Speicher allokieren matrix.buffer = (float *)malloc(rows * cols * sizeof(MatrixType)); } return matrix; } void clearMatrix(Matrix *matrix) { if (matrix->buffer != NULL) { 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(rowIdx >= matrix.rows || colIdx >= matrix.cols){ // Gültigkeit der Dimensionen prüfen return; } matrix.buffer[rowIdx * matrix.cols + colIdx] = value; // value an vorgebenener Stelle setzen } MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { if(rowIdx >= matrix.rows || colIdx >= matrix.cols){ // Gültigkeit der Dimensionen prüfen return 0; } MatrixType value; value = matrix.buffer[rowIdx * matrix.cols + colIdx]; // value an vorgegebener Stelle auslesen return value; } Matrix add(const Matrix matrix1, const Matrix matrix2) { size_t rows = (matrix1.rows > matrix2.rows) ? matrix1.rows : matrix2.rows; size_t cols = (matrix1.cols > matrix2.cols) ? matrix1.cols : matrix2.cols; // Prüfen, ob Broadcasting möglich ist if (!((matrix1.rows == rows || matrix1.rows == 1) && (matrix2.rows == rows || matrix2.rows == 1) && (matrix1.cols == cols || matrix1.cols == 1) && (matrix2.cols == cols || matrix2.cols == 1))) { Matrix errorMatrix = createMatrix(0, 0); return errorMatrix; } Matrix result = createMatrix(rows, cols); for (size_t i = 0; i < rows; i++) { for (size_t j = 0; j < cols; j++) { MatrixType val1 = matrix1.buffer[(i % matrix1.rows) * matrix1.cols + (j % matrix1.cols)]; MatrixType val2 = matrix2.buffer[(i % matrix2.rows) * matrix2.cols + (j % matrix2.cols)]; result.buffer[i * cols + j] = val1 + val2; } } return result; } Matrix multiply(const Matrix matrix1, const Matrix matrix2) { if (matrix1.cols != matrix2.rows){ // prüfen, ob Matrizen multipliziert werden dürfen Matrix errorMatrix = createMatrix(0, 0); errorMatrix.buffer = NULL; return errorMatrix; } Matrix matrix3 = createMatrix(matrix1.rows, matrix2.cols); // Ergebnis-Matrix erstellen // Algorithmus für Multiplikation for( size_t i = 0; i < matrix1.rows; i++){ for(size_t j = 0; j < matrix2.cols; j++){ MatrixType sum = 0; for(size_t k = 0; k < matrix1.cols; k++){ sum += getMatrixAt(matrix1, i, k) * getMatrixAt(matrix2, k, j); } setMatrixAt(sum, matrix3, i, j); } } return matrix3; }