#include #include #include "matrix.h" // TODO Matrix-Funktionen implementieren Matrix createMatrix(unsigned int rows, unsigned int cols) { Matrix matrix; if (rows == 0 || cols == 0) { matrix.rows = 0; matrix.cols = 0; matrix.buffer = NULL; return matrix; } matrix.buffer = malloc(rows*cols*sizeof(MatrixType)); if (matrix.buffer == NULL) { matrix.rows = 0; matrix.cols = 0; matrix.buffer = NULL; return matrix; } matrix.rows = rows; matrix.cols = cols; 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.rows <= rowIdx || matrix.cols <= colIdx) { return; } unsigned int index = rowIdx * matrix.cols + colIdx; matrix.buffer[index] = value; } MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { if(matrix.rows <= rowIdx || matrix.cols <= colIdx){ return UNDEFINED_MATRIX_VALUE; } unsigned int index = rowIdx * matrix.cols + colIdx; return matrix.buffer[index]; } Matrix add(const Matrix matrix1, const Matrix matrix2) { if(matrix1.rows == matrix2.rows && matrix1.cols == matrix2.cols) { Matrix resultMatrix = createMatrix(matrix1.rows, matrix1.cols); for (unsigned int i = 0; i < matrix1.rows*matrix1.cols; i++) { resultMatrix.buffer[i]=matrix1.buffer[i]+matrix2.buffer[i]; } return resultMatrix; } else if (matrix1.rows == matrix2.rows && (matrix1.cols == 1 || matrix2.cols == 1)) { Matrix resultMatrix; if (matrix2.cols == 1) { resultMatrix = createMatrix(matrix1.rows, matrix1.cols); for (unsigned int i = 0; i < matrix1.rows*matrix1.cols; i++) { unsigned int rowIdx = i / matrix1.cols; resultMatrix.buffer[i] = matrix1.buffer[i] + matrix2.buffer[rowIdx]; } } else{ resultMatrix = createMatrix(matrix2.rows, matrix2.cols); for (unsigned int i = 0; i < matrix2.rows*matrix2.cols; i++) { unsigned int rowIdx = i / matrix2.cols; resultMatrix.buffer[i] = matrix2.buffer[i] + matrix1.buffer[rowIdx]; } } return resultMatrix; } else { Matrix result; result.rows = 0; result.cols = 0; result.buffer = NULL; return result; } } Matrix multiply(const Matrix matrix1, const Matrix matrix2) { if(matrix.cols !=matrix2.rows){ Matrix result; result.rows = 0; result.cols = 0; result.buffer = NULL; return result; } Matrix resultMatrix = createMatrix(matrix1.rows, matrix2.cols); if (resultMatrix.buffer == NULL) { return resultMatrix; } 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++) { sum += getMatrixAt(matrix1, i, j) * getMatrixAt(matrix2, k, j); } setMatrixAt(sum, resultMatrix, i, j); } } return resultMatrix; }