generated from freudenreichan/info2Praktikum-NeuronalesNetz
Matrix Funktionen implementiert und getestet
This commit is contained in:
1 parent
cb6e2fb7a2
commit
6d9aa3709a
1 file changed
+68
@@ -44,24 +44,92 @@ void clearMatrix(Matrix *matrix)
|
||||
matrix->cols = 0;
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
void setMatrixAt(MatrixType value, 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] = value;
|
||||
|
||||
|
||||
}
|
||||
|
||||
MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
|
||||
{
|
||||
if (matrix.buffer == NULL ||
|
||||
rowIdx >= matrix.rows ||
|
||||
colIdx >= matrix.cols) {
|
||||
return UNDEFINED_MATRIX_VALUE;
|
||||
}
|
||||
|
||||
return matrix.buffer[rowIdx * matrix.cols + colIdx];
|
||||
}
|
||||
|
||||
Matrix add(const Matrix matrix1, const Matrix matrix2)
|
||||
{
|
||||
|
||||
if (matrix1.rows != matrix2.rows ||
|
||||
(matrix1.cols != matrix2.cols &&
|
||||
matrix1.cols != 1 &&
|
||||
matrix2.cols != 1)) {
|
||||
return createMatrix(0, 0);
|
||||
}
|
||||
|
||||
// Ungültige Eingabematrizen abfangen
|
||||
if (matrix1.buffer == NULL || matrix2.buffer == NULL) {
|
||||
return createMatrix(0, 0);
|
||||
}
|
||||
|
||||
// Größere Spaltenanzahl bestimmen
|
||||
unsigned int cols = matrix1.cols > matrix2.cols
|
||||
? matrix1.cols : matrix2.cols;
|
||||
|
||||
Matrix result = createMatrix(matrix1.rows, cols);
|
||||
|
||||
if (result.buffer == NULL) {
|
||||
return result;
|
||||
}
|
||||
|
||||
for (unsigned int i = 0; i < result.rows; i++) {
|
||||
for (unsigned int j = 0; j < result.cols; j++) {
|
||||
|
||||
// Bei einer Spalte immer Spalte 0 verwenden
|
||||
unsigned int j1 = matrix1.cols == 1 ? 0 : j;
|
||||
unsigned int j2 = matrix2.cols == 1 ? 0 : j;
|
||||
|
||||
result.buffer[i * result.cols + j] =
|
||||
matrix1.buffer[i * matrix1.cols + j1] +
|
||||
matrix2.buffer[i * matrix2.cols + j2];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
Matrix multiply(const Matrix matrix1, const Matrix matrix2)
|
||||
{
|
||||
if (matrix1.cols != matrix2.rows) {
|
||||
return createMatrix(0, 0);
|
||||
}
|
||||
|
||||
// Ergebnismatrix erstellen
|
||||
Matrix result = createMatrix(matrix1.rows, matrix2.cols);
|
||||
|
||||
// Matrizen multiplizieren
|
||||
for (unsigned int rowIdx = 0; rowIdx < matrix1.rows; rowIdx++) {
|
||||
for (unsigned int colIdx = 0; colIdx < matrix2.cols; colIdx++) {
|
||||
for (unsigned int k = 0; k < matrix1.cols; k++) {
|
||||
result.buffer[rowIdx * result.cols + colIdx] +=
|
||||
matrix1.buffer[rowIdx * matrix1.cols + k] *
|
||||
matrix2.buffer[k * matrix2.cols + colIdx];
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Reference in new issue
Block a user