Here is my code:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *infile;
int row, col, rows, cols;
double **a, *b, *c, sum;
/* Define infile */
infile = fopen("matrix5.dat", "r");
/* read rows and cols */
fscanf(infile, "%d %d", &rows, &cols);
printf("Rows = %d Cols = %d\n", rows, cols);
/* Allocate memory to **a */
a=( double **)calloc((size_t)cols, sizeof(double *));
/* Allocate memory for a[row], row=0, 1, ..., rows-1 */
for(row=0; row<rows; row++){
a[row] = (double *)calloc((size_t)cols, sizeof(double));
}
/* Allocate memory for b[rows] and c[rows] */
b=(double *)calloc((size_t)cols, sizeof(double *));
c=(double *)calloc((size_t)cols, sizeof(double *));
/* read all rows and save the values in a[][] */
for(row=0; row<rows; row++){
for(col=0; col<cols; col++)
fscanf(infile, "%lf", a[row]+col);
}
/* read b[] from the last line */
for(col=0; col<cols; col++){
fscanf(infile, "%lf", b+col);
}
/* print a[][] */
for(row=0; row<rows; row++){
for(col=0; col<cols; col++)
printf("%9.3f ", a[row][col]);
printf("\n");
}
/* print b[] */
printf("\n");
for(col=0; col<cols; col++){
printf("%9.3f ", b[col]);
}
/* compute c[] = a[][] * b[] */
for(row=0; row<rows; row++){
for(col=0; col<cols; col++){
sum += a[row][col]*b[col];
}
c[row]=sum;
sum=0;
}
/* print c[] */
printf("\n");
for(row=0; row<rows; row++){
printf("%9.3f ", c[row]);
}
printf("\n");
/* return memory */
/* close infile */
fclose(infile);
}
When it multiplies the matrix, b[5] seems to take on the value of the previous answer, which was 44, throwing the rest of the answers off.
a[][] is a 7x7 matrix and b[] is a 1x7 matrix.
I seriously do not know what is wrong, I've been at it for hours. I'm using vi editor, compile with gcc.
Thanks!