Hey, so I have to make a program that has to multiply two 3x3 matrices (among other things). I used classes to do the project, but I just can't seem to get this multiplication to work. Here is my code so far:

``````void matrix::mult(const matrix& u)
{
double c[9];
double a[9];
for (int i=0; i<rows; i++)
{
for (int j=0; j<columns; j++)
{
for(int r=0; r<columns; r++)
{
c[i*columns+j]+=a[i*columns+r]*u.data[r*columns+j];
}
}
}
}``````

Any advice would be great, and please let me know if there's anything I should clarify. Thank You.

## All 4 Replies

First thing that comes to mind is that `a[9]` and `c[9]` are not initialized.

Next you are using variables columns and row. So check that this->rows == u.columns. Then set the data in this. as c[] is just ignored.

Other than that it looks ok.

Next you are using variables columns and row. So check that this->rows == u.columns. Then set the data in this. as c[] is just ignored.

Hey, thanks for replying. I'm not quite sure what you mean with the above though. And if it matters, rows and columns aren't actually variables, they're constants.

Why do you have 3 loops for a 1d vector?

If you want to emulate it as a 2d then all you need is 2 for loops.

``````int A[4] = {1,2,3,4};
int B[4] = {1,2,3,4};
int R[4] = {0};

for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
R[ j + 4*i] = A[j + 4*i] * B[j + 4*i];
}``````

Its better to make a function that converts (j+4*i) into a 2d index so it becomes more readable.

Hi.
Try this. Naive, but should give you some idea.
The way you architect the classes entirely depends on you.

``````#include<iostream>
using namespace std;
const int SIZE = 3;

class  Matrix{
public:
int matrix[SIZE][SIZE];
};

class MatOps{
public:
Matrix mul_matrix(Matrix &, Matrix &);
};

void Matrix :: read_matrix(){
cout<<"Enter matrix(3 x 3)"<<endl;
int i = 0;
int j = 0;
for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
cin>>matrix[i][j];
}
}//for ends

Matrix MatOps :: mul_matrix(Matrix & a, Matrix & b){
Matrix result;
int i = 0;
int j = 0;
int k = 0;

for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
result.matrix[i][j] = 0;
for(k = 0; k < SIZE; k++){
result.matrix[i][j] += a.matrix[i][k] * b.matrix[k][j];
}
}
}//for ends

return result;

int main(){
Matrix a, b;

MatOps obj;
Matrix result = obj.mul_matrix(a, b);

for(int i = 0; i < SIZE; i++){
for(int j = 0; j < SIZE; j++){
cout<<result.matrix[i][j]<<" ";
}
cout<<endl;
}

return 0;
}//main() ends``````

Cheers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.