Matrix Multiplication Functions


/* multiplies m1 and m2 together and puts the result in result */
void multiply3by3 (float m1[3][3], float m2[3][3], float result[3][3]) {
   int i, j, k;
   for (i=0; i < 3; ++i) {
      for (j=0; j < 3; ++j) {
         result[i][j] = 0;
         for (k=0; k < 3; ++k) {
            result[i][j] += m1[i][k] * m2[k][j];
         }
      }
   }
}

/* Input: 1. 3 by 3 conversion matrix
          2. A two dimensional array with 3 unsigned characters for each pixel in the image
          3. A count of the total number of pixels
   Output:   The result of multiplying the conversion matrix by each pixel's three values,
             stored as floats.
 */             
         
void matrix_mult_char2float (float matrix[3][3], unsigned char (*in)[3],
                   float (*out)[3], int num_pixels){
   int i, j, k;
   float result;
   for (i=0; i < num_pixels; ++i) {
      for (j=0; j < 3; ++j) {
         result = 0;
         for (k=0; k < 3; ++k) {
            result += in[i][k] * matrix[j][k];
         }
         out[i][j] = result;
      }
   }
}

/* Input: 1. 3 by 3 conversion matrix
          2. A two dimensional array with 3 floats for each pixel in the image
          3. A count of the total number of pixels
   Output:   The result of multiplying the conversion matrix by each pixel's three values,
             stored as unsigned characters.
 */             
void matrix_mult_float2char (float matrix[3][3], float (*in)[3],
                   unsigned char (*out)[3], int num_pixels){
   int i, j, k;
   float result;
   for (i=0; i < num_pixels; ++i) {
      for (j=0; j < 3; ++j) {

         result = .5; /* add .5 for rounding  */

         for (k=0; k < 3; ++k) {
            result += in[i][k] * matrix[j][k];
         }
         if (result > 255) result = 255;
         if (result < 0) result = 0;
         out[i][j] = result;
      }
   }
}

/* Input: 1. 3 by 3 conversion matrix
          2. A two dimensional array with 3 floats for each pixel in the image
          3. A count of the total number of pixels
   Output:   The result of multiplying the conversion matrix by each pixel's three values,
             stored as floats.
 */             
void matrix_mult_float2float (float matrix[3][3], float (*in)[3],
                   float (*out)[3], int num_pixels){
   int i, j, k;
   float result;
   for (i=0; i < num_pixels; ++i) {
      for (j=0; j < 3; ++j) {

         result = 0;

         for (k=0; k < 3; ++k) {
            result += in[i][k] * matrix[j][k];
         }
         out[i][j] = result;
      }
   }
}