97 lines
2.5 KiB
C

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "matrix.h"
// TODO Matrix-Funktionen implementieren
Matrix createMatrix(unsigned int rows, unsigned int cols)
{
if(rows == 0 || cols == 0){
Matrix matrixNull;
matrixNull.rows = 0;
matrixNull.cols = 0;
matrixNull.buffer = NULL;
return matrixNull;
}
Matrix matrix;
matrix.rows = rows;
matrix.cols = cols;
matrix.buffer = calloc(rows*cols, sizeof(MatrixType));
if(matrix.buffer == 0){
printf("Das erstellen der Matrix ist fehlgeschlagen");
clearMatrix(&matrix);
return matrix;
}
return matrix;
}
void clearMatrix(Matrix *matrix)
{
matrix->buffer = NULL;
matrix->rows = 0;
matrix->cols = 0;
free(matrix->buffer);
}
void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{
size_t index = rowIdx * matrix.cols + colIdx; //spingt die zeilen * Anzahl der spalten (Eine Zeile = Anzahl der Spalten lang); + springt noch anzahl an spalten bis zur irhctigen Position
matrix.buffer[index] = value;
}
MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{
if(rowIdx > matrix.rows -1 || colIdx > matrix.cols -1){
return 0;
}
size_t 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) {
printf("Die Matritzen koennen nicht addiert werden");
return createMatrix(0,0);
}
Matrix matrix = createMatrix(matrix1.rows, matrix1.cols);
for (int index = 0; index < matrix1.rows * matrix1.cols; index++){
matrix.buffer[index] = matrix1.buffer[index] + matrix2.buffer[index];
}
return matrix;
}
Matrix multiply(const Matrix matrix1, const Matrix matrix2)
{
if (matrix1.cols != matrix2.rows) {
printf("Die Matritzen koennen nicht multipliziert werden");
return createMatrix(0,0);;
}
Matrix matrix = createMatrix(matrix1.rows, matrix2.cols);
int index = 0;
float wert = 0.0;
for(int i = 0; i < matrix1.rows * matrix1.cols; i+=matrix1.cols){
for(int j = 0; j < matrix2.cols; j++){
for(int k = 0; k < matrix1.cols; k++){
wert += matrix1.buffer[i+k] * matrix2.buffer[j+k*matrix2.cols];
}
matrix.buffer[index] = wert;
wert = 0.0;
index++;
}
}
return matrix;
}