2025-11-27 20:08:31 +01:00

107 lines
3.9 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include "matrix.h"
Matrix createMatrix(unsigned int rows, unsigned int cols) {
Matrix m;
if (rows == 0 || cols == 0) {
m.rows = 0;
m.cols = 0;
m.buffer = NULL;
return m;
}
m.rows = rows;
m.cols = cols;
m.buffer = (MatrixType *)malloc(rows * cols * sizeof(MatrixType));
if (m.buffer == NULL) {
fprintf(stderr, "Fehler: Speicher konnte nicht allokiert werden.\n");
m.rows = m.cols = 0;
} else {
for (unsigned int i = 0; i < rows * cols; i++) {
m.buffer[i] = UNDEFINED_MATRIX_VALUE;
}
}
return m;
}
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) {
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 matrix.buffer[rowIdx * matrix.cols + colIdx];
}
return UNDEFINED_MATRIX_VALUE;
}
Matrix add(const Matrix matrix1, const Matrix matrix2) {
Matrix result = {0, 0, NULL};
// Prüfe Dimensionen und Broadcasting
if ((matrix1.rows == matrix2.rows && matrix1.cols == matrix2.cols) ||
(matrix1.rows == matrix2.rows && matrix2.cols == 1) ||
(matrix1.cols == matrix2.cols && matrix2.rows == 1) ||
(matrix2.rows == matrix1.rows && matrix1.cols == 1) ||
(matrix2.cols == matrix1.cols && matrix1.rows == 1)) {
result = createMatrix(matrix1.rows, matrix1.cols);
for (unsigned int i = 0; i < matrix1.rows; i++) {
for (unsigned int j = 0; j < matrix1.cols; j++) {
MatrixType val1 = getMatrixAt(matrix1, i, j);
MatrixType val2;
// Broadcasting
if (matrix2.rows == matrix1.rows && matrix2.cols == matrix1.cols) {
val2 = getMatrixAt(matrix2, i, j);
} else if (matrix2.rows == matrix1.rows && matrix2.cols == 1) {
val2 = getMatrixAt(matrix2, i, 0);
} else if (matrix2.rows == 1 && matrix2.cols == matrix1.cols) {
val2 = getMatrixAt(matrix2, 0, j);
} else if (matrix1.rows == matrix2.rows && matrix1.cols == 1) {
val2 = getMatrixAt(matrix2, i, 0);
} else if (matrix1.rows == 1 && matrix1.cols == matrix2.cols) {
val2 = getMatrixAt(matrix2, 0, j);
} else {
val2 = UNDEFINED_MATRIX_VALUE;
}
setMatrixAt(val1 + val2, result, i, j);
}
}
}
return result;
}
Matrix multiply(const Matrix matrix1, const Matrix matrix2) {
Matrix result = {0, 0, NULL};
if (matrix1.cols != matrix2.rows) {
return result; // inkompatible Dimensionen
}
result = createMatrix(matrix1.rows, matrix2.cols);
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, k) * getMatrixAt(matrix2, k, j);
}
setMatrixAt(sum, result, i, j);
}
}
return result;
}