Broadcasting implementiert

This commit is contained in:
maxgrf 2025-11-16 21:11:25 +01:00
parent e25875fac6
commit 3a6cf8a104

View File

@ -52,25 +52,54 @@ MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int co
Matrix add(const Matrix matrix1, const Matrix matrix2)
{
// test, if two matrix has exact size
if (matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols)
return createMatrix(0, 0);
Matrix result_add = createMatrix(matrix1.rows, matrix1.cols);
for (int r = 0; r < matrix1.rows; r++)
// check, equal rows
if (matrix1.rows == matrix2.rows)
{
for (int c = 0; c < matrix1.cols; c++)
{
// TODO: matrix_add initialisieren
// matrix_add[r][c] = matrix1[r][c] + matrix2[r][c]
Matrix result_add = createMatrix(matrix1.rows, matrix1.cols);
MatrixType sum = getMatrixAt(matrix1, r, c) + getMatrixAt(matrix2, r, c);
setMatrixAt(sum, result_add, r, c); // evtl re
// "Elementweise Addition": test, if two matrix has exact size
if (matrix1.rows == matrix2.rows && matrix1.cols == matrix2.cols)
{
for (int r = 0; r < matrix1.rows; r++)
{
for (int c = 0; c < matrix1.cols; c++)
{
// first version: matrix_add[r][c] = matrix1[r][c] + matrix2[r][c]
MatrixType sum = getMatrixAt(matrix1, r, c) + getMatrixAt(matrix2, r, c);
setMatrixAt(sum, result_add, r, c);
}
}
}
// "Broadcasting": matrix1 has 1 collum
else if (matrix1.cols == 1)
{
for (int r = 0; r < matrix1.rows; r++)
{
for (int c = 0; c < matrix2.cols; c++)
{
MatrixType sum = getMatrixAt(matrix2, r, c) + getMatrixAt(matrix1, r, 0);
setMatrixAt(sum, result_add, r, c);
}
}
}
// "Broadcasting": matrix2 has 1 collum
else if (matrix2.cols == 1)
{
for (int r = 0; r < matrix1.rows; r++)
{
for (int c = 0; c < matrix1.cols; c++)
{
MatrixType sum = getMatrixAt(matrix1, r, c) + getMatrixAt(matrix2, r, 0);
setMatrixAt(sum, result_add, r, c);
}
}
}
return result_add;
}
return result_add;
else if (matrix1.rows == matrix2.rows && matrix1.cols == matrix2.cols)
return createMatrix(0, 0);
}
Matrix multiply(const Matrix matrix1, const Matrix matrix2)