/******************************************************** % % Written by: % -- % John L. Weatherwax 2005-05-25 % % email: wax@alum.mit.edu % % Please send comments and especially bug reports to the % above email address. % %----- A simple serial matrix multiplication program (Matrix_A X Matrix_B) => Matrix_C */ #include #include int **wMA,**wMB,**wMC; /* * Main: allocates matrix, assigns values, computes the results */ extern int main(int argc, char* argv[]) { int size, row, column; int i,j; /* Check input arguments */ if( argc < 2 | argc > 2 ){ fprintf(stderr,"Expecting one input argument: *n* (size of matrices)\n"); exit(1); } /* Extract out the requested matrix size */ size = atoi(argv[1]); if( size <= 0 ){ fprintf(stderr,"Input argument *n* must be positive\n"); exit(1); } /* Create space for the matrices: */ /* wMA: */ wMA = (int**) malloc( size * sizeof(int*) ); if( !wMA ){ fprintf(stderr,"Memory couldn't be created\n"); exit(1); } for( row=0; row < size; row++ ){ wMA[row] = malloc( size*sizeof(int) ); if( !wMA[row] ){ fprintf(stderr,"Memory couldn't be created\n"); exit(1); } } /* wMB: */ wMB = (int**) malloc( size * sizeof(int*) ); if( !wMB ){ fprintf(stderr,"Memory couldn't be created\n"); exit(1); } for( row=0; row < size; row++ ){ wMB[row] = malloc( size*sizeof(int) ); if( !wMB[row] ){ fprintf(stderr,"Memory couldn't be created\n"); exit(1); } } /* wMC: */ wMC = (int**) malloc( size * sizeof(int*) ); if( !wMC ){ fprintf(stderr,"Memory couldn't be created\n"); exit(1); } for( row=0; row < size; row++ ){ wMC[row] = malloc( size*sizeof(int) ); if( !wMC[row] ){ fprintf(stderr,"Memory couldn't be created\n"); exit(1); } } /* Fill in matrix values, currently values are hardwired */ for (row = 0; row < size; row++) { for (column = 0; column < size; column++) { wMA[row][column] = 1; } } for (row = 0; row < size; row++) { for (column = 0; column < size; column++) { wMB[row][column] = 1; } } for (row = 0; row < size; row++) { for (column = 0; column < size; column++) { wMC[row][column] = 0; } } /* Print matrices before: */ printf("MATRIX: The A array is;\n"); for(row = 0; row < size; row ++) { for (column = 0; column < size; column++) { printf("%5d ",wMA[row][column]); } printf("\n"); } printf("MATRIX: The B array is is;\n"); for(row = 0; row < size; row ++) { for (column = 0; column < size; column++) { printf("%5d ",wMB[row][column]); } printf("\n"); } /* Process Matrix, by row, column. */ for(row = 0; row < size; row++) { for (column = 0; column < size; column++) { for( i=0; i < size; i++ ) { wMC[row][column] += wMA[row][i]*wMB[i][column]; } } } /* Print results */ printf("MATRIX: The resulting matrix C is;\n"); for(row = 0; row < size; row ++) { for (column = 0; column < size; column++) { printf("%5d ",wMC[row][column]); } printf("\n"); } return 0; }