NeuronalesNetz/matrix.c

103 lines
2.4 KiB
C

#include "matrix.h"
#include <stdlib.h>
Matrix createMatrix(unsigned int rows, unsigned int cols)
{
if (rows == 0 || cols == 0) {
Matrix m = {0, 0, NULL};
return m;
}
Matrix m;
m.rows = rows;
m.cols = cols;
m.buffer = (MatrixType*)malloc(rows * cols * sizeof(MatrixType));
if (!m.buffer) {
m.rows = m.cols = 0;
}
return m;
}
void clearMatrix(Matrix *matrix)
{
if (!matrix || !matrix->buffer)
return;
free(matrix->buffer);
matrix->buffer = NULL;
matrix->rows = 0;
matrix->cols = 0;
}
MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{
if (rowIdx >= matrix.rows || colIdx >= matrix.cols)
return UNDEFINED_MATRIX_VALUE;
return matrix.buffer[rowIdx * matrix.cols + colIdx];
}
void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{
if (rowIdx >= matrix.rows || colIdx >= matrix.cols)
return;
matrix.buffer[rowIdx * matrix.cols + colIdx] = value;
}
Matrix add(const Matrix m1, const Matrix m2)
{
// Broadcasting unterstützt
if (m1.rows != m2.rows || (m1.cols != m2.cols && m1.cols != 1 && m2.cols != 1)) {
Matrix error = {0, 0, NULL};
return error;
}
unsigned int rows = m1.rows;
unsigned int cols = (m1.cols > m2.cols) ? m1.cols : m2.cols;
Matrix result = createMatrix(rows, cols);
if (!result.buffer)
return result;
for (unsigned int i = 0; i < rows; i++) {
for (unsigned int j = 0; j < cols; j++) {
MatrixType a = (m1.cols == 1) ? m1.buffer[i] : m1.buffer[i * m1.cols + j];
MatrixType b = (m2.cols == 1) ? m2.buffer[i] : m2.buffer[i * m2.cols + j];
result.buffer[i * cols + j] = a + b;
}
}
return result;
}
Matrix multiply(const Matrix m1, const Matrix m2)
{
if (m1.cols != m2.rows) {
Matrix error = {0, 0, NULL};
return error;
}
Matrix result = createMatrix(m1.rows, m2.cols);
if (!result.buffer)
return result;
for (unsigned int i = 0; i < m1.rows; i++) {
for (unsigned int j = 0; j < m2.cols; j++) {
MatrixType sum = 0;
for (unsigned int k = 0; k < m1.cols; k++)
sum += m1.buffer[i * m1.cols + k] * m2.buffer[k * m2.cols + j];
result.buffer[i * m2.cols + j] = sum;
}
}
return result;
}