Solution: Matrix Functions

Solution: Matrix Functions

C
#include <stdio.h>
typedef struct {
double data[1024]; // One-dimensional array stores data row-by-row
int nrows; // Number of rows
int ncols; // Number of columns
} Matrix;
void printMatrix(Matrix M);
Matrix matrixMult(Matrix A, Matrix B);
int main(void)
{
Matrix A = { {1.2, 2.3,
3.4, 4.5,
5.6, 6.7},
3,
2};
Matrix B = { {5.5, 6.6, 7.7,
1.2, 2.1, 3.3},
2,
3};
printMatrix(A);
printMatrix(B);
Matrix C = matrixMult(A, B);
printMatrix(C);
return 0;
}
void printMatrix(Matrix M){
int i, j;
printf("[\n");
for (i = 0; i < M.nrows; i++) {
for (j = 0; j < M.ncols; j++) {
printf("%6.3f ", M.data[i * M.ncols + j]);
}
printf("\n");
}
printf("]\n\n");
}
Matrix matrixMult(Matrix A, Matrix B)
{
Matrix C;
if (A.ncols != B.nrows) {
printf("Error: ncols of A does not equal nrows of B\n");
}
else {
int i, j, k;
double value;
for (i = 0; i < A.nrows; i++) {
for (j = 0; j < B.ncols; j++) {
value = 0.0;
for (k = 0; k < A.ncols; k++) {
value += A.data[i * A.ncols + k] * B.data[k * B.ncols + j];
}
C.data[i * A.nrows + j] = value;
}
}
C.nrows = A.nrows;
C.ncols = B.ncols;
}
return C;
}