forked from freudenreichan/info2Praktikum-NeuronalesNetz
69 lines
2.4 KiB
C
69 lines
2.4 KiB
C
#include "matrix.h"
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
// TODO Matrix-Funktionen implementieren
|
|
/*typedef struct {
|
|
unsigned int rows; //Zeilen
|
|
unsigned int cols; //Spalten
|
|
MatrixType *buffer; //Zeiger auf Speicherbereich Reihen*Spalten
|
|
} Matrix;*/
|
|
Matrix createMatrix(unsigned int rows, unsigned int cols) {
|
|
MatrixType *buffer =
|
|
malloc(rows * cols * sizeof(MatrixType)); // Speicher reservieren, malloc
|
|
// liefert Zeiger auf Speicher
|
|
Matrix newMatrix = {rows, cols, buffer}; // neue Matrix nach struct
|
|
return newMatrix;
|
|
}
|
|
void clearMatrix(Matrix *matrix) {
|
|
matrix->buffer = UNDEFINED_MATRIX_VALUE;
|
|
matrix->rows = UNDEFINED_MATRIX_VALUE;
|
|
matrix->cols = UNDEFINED_MATRIX_VALUE;
|
|
free((*matrix).buffer); // Speicher freigeben
|
|
}
|
|
void setMatrixAt(const MatrixType value, Matrix matrix,
|
|
const unsigned int rowIdx, // Kopie der Matrix wird übergeben
|
|
const unsigned int colIdx) {
|
|
|
|
matrix.buffer[rowIdx * matrix.cols + colIdx] =
|
|
value; // rowIdx * matrix.cols -> Beginn der Zeile colIdx ->Spalte
|
|
// innerhalb der Zeile
|
|
}
|
|
MatrixType getMatrixAt(const Matrix matrix,
|
|
unsigned int rowIdx, // Kopie der Matrix wird übergeben
|
|
unsigned int colIdx) {
|
|
if (rowIdx >= matrix.rows ||
|
|
colIdx >= matrix.cols) { // Speichergröße nicht überschreiten
|
|
return 0;
|
|
}
|
|
|
|
MatrixType value = matrix.buffer[rowIdx * matrix.cols + colIdx];
|
|
|
|
return value;
|
|
}
|
|
Matrix add(const Matrix matrix1, const Matrix matrix2) {
|
|
Matrix result;
|
|
const int cols1 = matrix1.cols;
|
|
const int rows1 = matrix1.rows;
|
|
const int cols2 = matrix2.cols;
|
|
const int rows2 = matrix2.rows;
|
|
const int colsEqu = (matrix1.cols == matrix2.cols) ? 1 : 0;
|
|
const int rowsEqu = (matrix1.rows == matrix2.rows) ? 1 : 0;
|
|
if(colsEqu && rowsEqu)
|
|
{
|
|
Matrix result = createMatrix(matrix1.rows, matrix1.cols);
|
|
for(int i = 0; i < rows1; i++)
|
|
{
|
|
for (int j = 0; j < cols1; j++)
|
|
{
|
|
int valueM1 = getMatrixAt(matrix1, i, j);
|
|
int valueM2 =getMatrixAt(matrix2, i, j);
|
|
int sum = valueM1 + valueM2;
|
|
setMatrixAt(sum, result,i,j);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
}
|
|
Matrix multiply(const Matrix matrix1, const Matrix matrix2) { return matrix1; }
|