Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to multiply matrices of different sizes?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]);
    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading