COMPARATIVE LANGUAGES
Fall 2005
Multiplying Matrices

  1. M1 has 'rows1' and 'cols1' number of rows and columns
    M2 has 'rows2' and 'cols2' number of rows and columns

  2. 'cols1' must be equal to 'rows2' in order to multiply M1 x M2

  3. The resulting product matrix has 'rows1' and 'cols2' number of rows and columns

  4.    loop i from 1 to rows1
          loop j from 1 to cols2
             set the product matrix(i,j) to 0 before the innermost loop
             loop k from 1 to cols1 (or rows2, since cols1 = rows2 in matrix multiplication)
                prod(i,j) = prod(i,j) + M1(?, ?) * M2(?, ?)
    
       - For prod(1,1) multiply M1(row=1, all columns) - the first row of M1- times
                                M2(column 1, all rows) - the first column of M2
       - For prod(1,2) multiply M1(row=1, all columns) - the first row of M1- times
                                M2(column 2, all rows) - the 2nd column of M2
       - For prod(1,3) multiply M1(row=1, all columns) - the first row of M1- times
                                M2(column 3, all rows) - the 3rd column of M2
    	  etc...
    
       - For prod(2,1) multiply M1(row=2, all columns) - the 2nd row of M1- times
                                M2(column 1, all rows) - the first column of M2
       - For prod(2,2) multiply M1(row=2, all columns) - the 2nd row of M1- times
                                M2(column 2, all rows) - the 2nd column of M2
       - For prod(2,3) multiply M1(row=2, all columns) - the 2nd row of M1- times
                                M2(column 3, all rows) - the 3rd column of M2
    
              etc...
    
       - For prod(3,1) multiply M1(row=3, all columns) - the 3rd row of M1- times
                                M2(column 1, all rows) - the first column of M2
       - For prod(3,2) multiply M1(row=3, all columns) - the 3rd row of M1- times
                                M2(column 2, all rows) - the 2nd column of M2
       - For prod(3,3) multiply M1(row=3, all columns) - the 3rd row of M1- times
                                M2(column 3, all rows) - the 3rd column of M2
    
             etc...
    
    
    Sample multiplication to check your work:
    
    Matrix m (2 rows, 4 cols):
    	 1 2 3 4
    	 5 6 7 8
    	 
    Matrix n (4 rows, 3 cols):
    	 1 2 3
    	 4 5 6
    	 7 8 9
    	 10 11 12
    
    Product matrix (2 rows, 3 cols):
    	 70 80 90
    	 158 184 210