# Matrix multiplication using 1-d arrays

• 05-25-2003
Befuddled
Matrix multiplication using 1-d arrays
I know how to properly multiply matrices, so that isn't the problem.

However, I'm working on a program that multiplies 2 dynamically created matrices, but the data is stored in one dimensional arrays. I thought it would be easier than creating an array of pointers that would point to arrays, but I can't figure out how to properly implement matrix multiplication on the 2 arrays.

In the followoing code, Matrix is a struct containing (int Row, int Col, and int *Data). Of course, this code doesn't multiply properly:

Code:

```void matrixMultiply(int MatrixOne, int MatrixTwo) {     cout << "Multiplying..." << endl;     int colCount = 0,         rowInc = 0,         colInc = 0,         Mat1Size = mList[MatrixOne].Row * mList[MatrixOne].Col,         Mat2Size = mList[MatrixTwo].Row * mList[MatrixTwo].Col;         Matrix Answer; //creates answer matrix     Answer.Row = mList[MatrixOne].Row;     Answer.Col = mList[MatrixTwo].Col;     Answer.Data = new int[Answer.Row*Answer.Col]; //allocates matrix space     for (int ii = 0; ii < Answer.Row*Answer.Col; ii++)     {         Answer.Data[ii] = 0; //initializes all data content to zero     }     for (int Count = 0; Count < Answer.Row*Answer.Col; Count++)     {         colCount = 0;         colInc = 0;         for (int rowCount = rowInc; rowCount < mList[MatrixOne].Row + rowInc; rowCount++)         { //adding and multiplying rows/cols             if (rowCount > Mat1Size)                 break;             Answer.Data[Count] += (mList[MatrixOne].Data[rowCount] * mList[MatrixTwo].Data[colCount]);             colCount += mList[MatrixTwo].Col;             if (colCount > Mat2Size)             {                 colInc++;                 colCount = colInc;             }         }         rowInc += mList[MatrixOne].Row;     }     matrixOutput(Answer); }```
Any help would be greatly appreciated.
• 05-25-2003
Prelude
>I thought it would be easier than creating an array of pointers that would point to arrays
Which would be easier? A little discomfort when you create an array of arrays out of a char**, or constant frustration in indexing a single dimension array so that you can fake multidimensional access?
• 05-25-2003
7stud
"I thought it would be easier than creating an array of pointers that would point to arrays..."

Apparently not. If you create the pseudo 2d arrays dynamically, then it's very straighforward to multiply two arrays together;
Code:

```int** matrix1; int** matrix2; int** matrix3; for(int i=0; i<rows; i++)   for(int j=0; j<columns; j++)       matrix3[i][j] = matrix1[i][j]*matrix2[i][j];```