forked from freudenreichan/info2Praktikum-NeuronalesNetz
70 lines
1.7 KiB
C
70 lines
1.7 KiB
C
#include "matrix.h"
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
// TODO Matrix-Funktionen implementieren
|
|
|
|
Matrix createMatrix(unsigned int rows, unsigned int cols)
|
|
{
|
|
Matrix matrix;
|
|
matrix.rows = rows;
|
|
matrix.cols = cols;
|
|
matrix.buffer = NULL;
|
|
if (rows == 0 || cols == 0)
|
|
{
|
|
return;
|
|
}
|
|
matrix.buffer = malloc(rows * cols * sizeof(MatrixType));
|
|
return matrix;
|
|
}
|
|
|
|
void clearMatrix(Matrix *matrix)
|
|
{
|
|
free(matrix->buffer);
|
|
}
|
|
|
|
void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
|
|
{
|
|
matrix.buffer[rowIdx * matrix.cols + colIdx] = value;
|
|
}
|
|
|
|
MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
|
|
{
|
|
MatrixType MatrixAt = matrix.buffer[rowIdx * matrix.cols + colIdx];
|
|
return MatrixAt;
|
|
}
|
|
|
|
Matrix add(const Matrix matrix1, const Matrix matrix2)
|
|
{
|
|
Matrix MatrixAdd = createMatrix(matrix1.rows, matrix1.cols);
|
|
for (int i = 0; i < matrix1.rows; i++)
|
|
{
|
|
for (int j = 0; j < matrix1.cols; j++)
|
|
{
|
|
MatrixType val1 = getMatrixAt(matrix1, i, j);
|
|
MatrixType val2 = getMatrixAt(matrix2, i, j);
|
|
setMatrixAt(val1 + val2, MatrixAdd, i, j);
|
|
}
|
|
}
|
|
return MatrixAdd;
|
|
}
|
|
|
|
Matrix multiply(const Matrix matrix1, const Matrix matrix2)
|
|
{
|
|
Matrix MatrixMult = createMatrix(matrix1.rows, matrix2.cols);
|
|
for (int i = 0; i < matrix1.rows; i++)
|
|
{
|
|
for (int j = 0; j < matrix2.cols; j++)
|
|
{
|
|
MatrixType skalar = 0;
|
|
for (int k = 0; k < matrix1.cols; k++)
|
|
{
|
|
MatrixType val1 = getMatrixAt(matrix1, i, k);
|
|
MatrixType val2 = getMatrixAt(matrix2, k, j);
|
|
skalar += val1 * val2;
|
|
}
|
|
setMatrixAt(skalar, MatrixMult, i, j);
|
|
}
|
|
}
|
|
return MatrixMult;
|
|
} |