Make a program that read the contents of two matrices and return a matrix with the result of the multiplication.

Multiply two matrices.

Show result in another matrix

Printable View

- July 2nd 2008, 10:48 AMApprentice123Language C ---matrix----
Make a program that read the contents of two matrices and return a matrix with the result of the multiplication.

Multiply two matrices.

Show result in another matrix - July 2nd 2008, 01:07 PMReckoner
How are the matrices being entered? Through a file? Command-line parameters? Through the console?

Anyway, you can represent the matrices with arrays (you can use two-dimensional arrays, but one-dimensional is easier to work with):

Try something like this (note that this was quickly written, untested, untried, and comes with no guarantees; I leave it to you to make it look "prettier" and add proper error checking):

Code:`/* m_mult - Multiply two matrices`

* result: a pointer to an array of ints of size rows1 * cols2 (allocate beforehand)

* m1: pointer to the first matrix (array with entries ordered by row and then by column--e.g., ordered such that row m column n is given by m1[m*cols1 + n])

* rows1: number of rows in first matrix

* cols1: number of columns in first matrix

* m2: pointer to second matrix

* rows2: number of rows in second matrix

* cols2: number of columns in second matrix

*/

void m_mult(int* result, int* m1, int rows1, int cols1, int* m2, int rows2, int cols2)

{

if( (rows1 != cols2) || (rows2 != cols1) ) {

//Can't multiply these matrices

return;

}

//Iterate through each row of the resultant matrix

for(int i = 0; i < rows1; ++i) {

//Iterate through each column of the resultant matrix

for(int j = 0; j < cols2; ++j) {

//Element i, j of the resultant is given by the dot product of row i of m1 with col j of m2

int product = 0;

for(int entry = 0; entry < rows2; ++entry) {

product += m1[i*cols1 + entry] * m2[entry*cols2 + j];

}

//Store the product in row i column j

result[i*cols2 + j] = product;

}

}

}