getMatrixAt und multiply

This commit is contained in:
Laila Mueller 2025-11-09 22:54:09 +01:00
parent 6d5b19eb76
commit d354b45396

View File

@ -34,7 +34,12 @@ void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned
MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{ {
if(rowIdx > matrix.rows || colIdx > matrix.cols){
return 0;
}
MatrixType value;
value = matrix.data[rowIdx * matrix.cols + colIdx];
return value;
} }
Matrix add(const Matrix matrix1, const Matrix matrix2) Matrix add(const Matrix matrix1, const Matrix matrix2)
@ -44,7 +49,24 @@ Matrix add(const Matrix matrix1, const Matrix matrix2)
Matrix multiply(const Matrix matrix1, const Matrix matrix2) Matrix multiply(const Matrix matrix1, const Matrix matrix2)
{ {
if (matrix1.cols != matrix2.rows){
Matrix errorMatrix = createMatrix(0, 0);
errorMatrix.data = NULL;
return errorMatrix;
}
Matrix matrix3 = createMatrix(matrix1.rows, matrix2.cols);
for( size_t i = 0; i < matrix1.rows; i++){
for(size_t j = 0; j < matrix2.cols; j++){
MatrixType sum = 0;
for(size_t k = 0; k < matrix1.cols; k++){
sum += getMatrixAt(matrix1, i, k) * getMatrixAt(matrix2, k, j);
}
setMatrixAt(sum, matrix3, i, j);
}
}
return matrix3;
} }