#include #include #include "matrix.h" #include // TODO Matrix-Funktionen implementieren Matrix createMatrix(unsigned int rows, unsigned int cols) { if(rows == 0 || cols == 0) { return (Matrix){0}; } Matrix Mat; Mat.rows = rows; Mat.cols = cols; Mat.buffer = malloc(rows*cols*(sizeof(MatrixType))); return Mat; } void clearMatrix(Matrix *matrix) { free(matrix->buffer); matrix->buffer = NULL; matrix->cols = 0; matrix->rows = 0; } void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { if (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 (rowIdx >= matrix.rows || colIdx >= matrix.cols) { return (MatrixType)0; } return matrix.buffer[rowIdx * matrix.cols + colIdx]; } Matrix add(const Matrix matrix1, const Matrix matrix2) { Matrix result; // Fall 1: Elementweise Addition if (matrix1.cols == matrix2.cols && matrix1.rows == matrix2.rows) { result = createMatrix(matrix1.rows, matrix1.cols); for (int i = 0; i < result.rows * result.cols; i++) { result.buffer[i] = matrix1.buffer[i] + matrix2.buffer[i]; } } // Fall 2: Broadcasting else if (matrix1.rows == matrix2.rows && (matrix1.cols == 1 || matrix2.cols == 1)) { result = createMatrix(matrix1.rows, ((matrix1.cols > matrix2.cols) ? matrix1.cols : matrix2.cols)); for (int row = 0; row < result.rows; row++) { for (int col = 0; col < result.cols; col++) { int index = row * result.cols + col; int index1 = row * matrix1.cols + (matrix1.cols == 1 ? 0 : col); int index2 = row * matrix2.cols + (matrix2.cols == 1 ? 0 : col); result.buffer[index] = matrix1.buffer[index1] + matrix2.buffer[index2]; } } } // Ungültige Größen else { result = createMatrix(0, 0); } return result; } Matrix multiply(const Matrix matrix1, const Matrix matrix2) { Matrix result; // Prüfen, ob die Multiplikation möglich ist if (matrix1.cols != matrix2.rows){ return createMatrix(0, 0); } // Ergebnis-Matrix erstellen result = createMatrix(matrix1.rows, matrix2.cols); // Matrizen multiplizieren for (int row = 0; row < result.rows; row++) { for (int col = 0; col < result.cols; col++) { MatrixType sum = 0; for (int k = 0; k < matrix1.cols; k++){ sum += matrix1.buffer[row * matrix1.cols + k] * matrix2.buffer[k * matrix2.cols + col]; } result.buffer[row * result.cols + col] = sum; } } return result; }