forked from freudenreichan/info2Praktikum-NeuronalesNetz
131 lines
2.8 KiB
C
131 lines
2.8 KiB
C
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include "matrix.h"
|
|
|
|
// Matrix erstellen
|
|
Matrix createMatrix(unsigned int rows, unsigned int cols)
|
|
{
|
|
Matrix matrix;
|
|
|
|
matrix.rows = rows;
|
|
matrix.cols = cols;
|
|
|
|
matrix.buffer = calloc(rows * cols, sizeof(MatrixType));
|
|
|
|
if (matrix.buffer == NULL)
|
|
{
|
|
matrix.rows = 0;
|
|
matrix.cols = 0;
|
|
}
|
|
|
|
return matrix;
|
|
}
|
|
|
|
// Matrix-Speicher freigeben
|
|
void clearMatrix(Matrix* matrix)
|
|
{
|
|
if (matrix != NULL)
|
|
{
|
|
free(matrix->buffer);
|
|
|
|
matrix->buffer = NULL;
|
|
matrix->rows = 0;
|
|
matrix->cols = 0;
|
|
}
|
|
}
|
|
|
|
// Wert an einer bestimmten Position setzen
|
|
void setMatrixAt(MatrixType value, Matrix matrix,
|
|
unsigned int rowIdx, unsigned int colIdx)
|
|
{
|
|
if (matrix.buffer != NULL &&
|
|
rowIdx < matrix.rows &&
|
|
colIdx < matrix.cols)
|
|
{
|
|
matrix.buffer[rowIdx * matrix.cols + colIdx] = value;
|
|
}
|
|
}
|
|
|
|
// Wert an einer bestimmten Position auslesen
|
|
MatrixType getMatrixAt(const Matrix matrix,
|
|
unsigned int rowIdx, unsigned int colIdx)
|
|
{
|
|
if (matrix.buffer != NULL &&
|
|
rowIdx < matrix.rows &&
|
|
colIdx < matrix.cols)
|
|
{
|
|
return matrix.buffer[rowIdx * matrix.cols + colIdx];
|
|
}
|
|
|
|
return UNDEFINED_MATRIX_VALUE;
|
|
}
|
|
|
|
// Zwei Matrizen addieren
|
|
Matrix add(const Matrix matrix1, const Matrix matrix2)
|
|
{
|
|
if (matrix1.rows != matrix2.rows ||
|
|
matrix1.cols != matrix2.cols ||
|
|
matrix1.buffer == NULL ||
|
|
matrix2.buffer == NULL)
|
|
{
|
|
return createMatrix(0, 0);
|
|
}
|
|
|
|
Matrix result = createMatrix(matrix1.rows, matrix1.cols);
|
|
|
|
if (result.buffer == NULL)
|
|
{
|
|
return result;
|
|
}
|
|
|
|
for (unsigned int i = 0; i < matrix1.rows; i++)
|
|
{
|
|
for (unsigned int j = 0; j < matrix1.cols; j++)
|
|
{
|
|
MatrixType value =
|
|
getMatrixAt(matrix1, i, j) +
|
|
getMatrixAt(matrix2, i, j);
|
|
|
|
setMatrixAt(value, result, i, j);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// Zwei Matrizen multiplizieren
|
|
Matrix multiply(const Matrix matrix1, const Matrix matrix2)
|
|
{
|
|
if (matrix1.cols != matrix2.rows ||
|
|
matrix1.buffer == NULL ||
|
|
matrix2.buffer == NULL)
|
|
{
|
|
return createMatrix(0, 0);
|
|
}
|
|
|
|
Matrix result = createMatrix(matrix1.rows, matrix2.cols);
|
|
|
|
if (result.buffer == NULL)
|
|
{
|
|
return result;
|
|
}
|
|
|
|
for (unsigned int i = 0; i < matrix1.rows; i++) // nur < weil bei 0 angefangen zu zählen
|
|
{
|
|
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;
|
|
}
|