Home > Net >  How to multiply matrices of different sizes?
How to multiply matrices of different sizes?

Time:11-12

I am trying to multiply matrices of different sizes. Generally if the matrix has the same size you would use 2 for loops, but what about matrices with different sizes?

int main(int argc, char const *argv[]) {
  int mat1[2][3] ={{1,2,3},
                  {4,5,6},
                  };
  int mat2[3][2] = {{1,2},
                    {3,4},
                    {6,5}
                   };

int *pointerToMat1 = &mat1[0][0];
int *pointerToMat2 = &mat2[0][0];



  return 0;
}

I was thinking to use pointers but I got lost. The above example is just to test the function, in general matrixProduct should work for any size matrices, as long as mathematical rules hold.

CodePudding user response:

Well.. The formula for matrix multiplication is pretty straightforward:

Multiplying A(MxN) and B(NxM) gives C(MxM):

C[i,j] = sum ( A[i,k]*B[k,j] k = 0..N ) ; i,j=0..M

So with your code I would do:

#include <stdio.h>

int main()
{
      int mat1[2][3] ={{1,2,3},
                  {4,5,6},
                  };
      int mat2[3][2] = {{1,2},
                        {3,4},
                        {6,5}
                       };
    
    int *pointerToMat1 = &mat1[0][0];
    int *pointerToMat2 = &mat2[0][0];
    
    
    int C[2][2];
    for ( int i=0; i<2; i  ) {
        for( int j=0;j<2;j   ) {
           C[i][j] = 0;
           for( int k=0;k<3;k   ) {
               printf("%dx%d=%d\n",mat1[i][k],mat2[k][j],mat1[i][k]*mat2[k][j]);
              C[i][j]  = mat1[i][k]*mat2[k][j];
           } 
        }
    }
    
    printf("%d %d %d %d",C[0][0],C[0][1],C[1][0],C[1][1]);
    
}
  • Related