Matrix Multiplication

Hi.
What's wrong with my Matrix Multiplication program?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int  main()
{
     float A[][3] =  { {7./15, 7./15, 1./15}, {7./15, 1./15, 1./15}, {1./15, 7./15, 13./15} }
     , r[] = {1/3, 1/3, 1/3}, sum[3]={0};
     
     while( (sum[0]!= r[0]) || (sum[1] != r[1]) ||(sum[2]!= r[2]) )
     {
        for(int row = 0;row <3;++row)  
          for(int i =0;i<3;++i)
             sum[i] += A[row][i] * r[i];
        sum[0]=r[0];
        sum[1]=r[1];
        sum[2]=r[2];
     }
           
     cout << r[0] << ',' <<r[1] << ',' <<r[2];

for(;;);
     
     return 0;
}

it prints all zeros.
Last edited on
1/3 is equal to zero because of integer division. 1.f/3.f is approximately equal to one third.
While loop never enters because sum and r contain the same values. A loop shouldn't even be there, since it's not generally true that AB = B, where A and B are matrices.
Oops!

OK, I corrected it.Now all elements are printed as 1/3. This should not be the case
Okay hooshdar3, I saw your program and I have corrected it, I have some queries regarding your program.

But first I feel that I should provide you some details.

1. For matrix multiplication you need two matrices (say A and B) which are going to be multiplied and a third     matrix (say AxB) which will store the values of matrix multiplication.

2. For example the matrix A is of order 1x3 or 5x3 or 3x3 then matrix B must be of order 3x2 or 3x3 or 3x6.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream.h>
#include<conio.h>

int main()
{
clrscr(); //to clear the screen
int BxA[3]={0}, B[]={1,2,3}, A[][3]={ {1,2,3},
				      {1,2,3},
				      {1,2,3} }; 
//I changed the names of integer arrays so that you can link it with my explanation above.
//Here all the values of B[] and A[][] can be changed to any integer.

//while loop is not needed
for(int i=0;i<3;i++) //I changed the variable "row" to "i" for clarity 
 for(int j=0;j<3;j++)//I changed the variable "i" to "j" for clarity
  BxA[i]+= A[j][i]*B[j];

cout<<BxA[0]<<','<<BxA[1]<<','<<BxA[2];
getch(); // To halt the screen until any key is pressed
return 0;
}
Topic archived. No new replies allowed.