multiply
This commit is contained in:
parent
f2d35fb9d6
commit
4041322924
30
matrix.c
30
matrix.c
@ -85,6 +85,34 @@ Matrix add(const Matrix matrix1, const Matrix matrix2)
|
||||
}
|
||||
|
||||
Matrix multiply(const Matrix matrix1, const Matrix matrix2)
|
||||
{
|
||||
{ if (matrix1.cols != matrix2.rows){ // check compatibility
|
||||
Matrix empty = {.rows =0, .cols=0, .buffer =NULL};
|
||||
return empty;
|
||||
}
|
||||
unsigned int resultRows = matrix1.rows; // determine result dimensions
|
||||
unsigned int resultCols = matrix2.cols;
|
||||
|
||||
MatrixType *resultBuffer = malloc( resultRows * resultCols * sizeof(MatrixType)); // allocate memory
|
||||
if (resultBuffer == NULL){
|
||||
Matrix empty = {.rows =0, .cols=0, .buffer= NULL};
|
||||
return empty;
|
||||
}
|
||||
for (unsigned int i =0; i < resultRows; ++i){
|
||||
for (unsigned int j =0; j< resultCols; ++j){
|
||||
MatrixType sum = 0.0;
|
||||
for (unsigned int k =0; k< matrix1.cols; ++k){
|
||||
MatrixType val1 =getMatrixAt(matrix1, i,k);
|
||||
MatrixType val2 = getMatrixAt(matrix2, k,j);
|
||||
sum += val1 * val2;
|
||||
}
|
||||
|
||||
|
||||
unsigned int resultIndex = i * resultCols + j;
|
||||
resultBuffer [resultIndex] = sum;
|
||||
}
|
||||
}
|
||||
Matrix result = {.rows = resultRows, .cols = resultCols, .buffer =resultBuffer};
|
||||
return result;
|
||||
|
||||
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user