Matrix Multiplication

Hello,

I am trying to find an example of how to multiply two matrices (for example, two 3x3 matrices) in C. Does anyone know of any tutorials online that explain this? I know I have to use pointers but I'm having a hard time grasping how to do this task.

Thanks,
David

Comments

  • 3 Comments sorted by Date Added Votes
  • JasonDorieJasonDorie Posts: 1,806
    edited April 11 Vote Up0Vote Down
    This is the simplest (loop based, in C) form:
    void simple_mul(const float a[3][3], const float b[3][3], float out[3][3]) {
      int i,j,m,n;
      for(i=0;i<3;i++) {  // for each output row
        for(j=0;j<3;j++) {  // for each output column
          out[i][j] = 0.0f;  // zero the value being computed
          for(m=0;m<3;m++) {
            out[i][j] += a[i][m]*b[m][j];  // accumulate the row & column multiplies
          }
        }
      }
    }
    
    Expanded out, it looks more like this:
       void mult(const Matrix3D & a, const Matrix3D & b, Matrix3D & out)
        {
            out.M11 = a.M11 * b.M11 + a.M12 * b.M21 + a.M13 * b.M31;
            out.M12 = a.M11 * b.M12 + a.M12 * b.M22 + a.M13 * b.M32;
            out.M13 = a.M11 * b.M13 + a.M12 * b.M23 + a.M13 * b.M33;
            out.M21 = a.M21 * b.M11 + a.M22 * b.M21 + a.M23 * b.M31;
            out.M22 = a.M21 * b.M12 + a.M22 * b.M22 + a.M23 * b.M32;
            out.M23 = a.M21 * b.M13 + a.M22 * b.M23 + a.M23 * b.M33;
            out.M31 = a.M31 * b.M11 + a.M32 * b.M21 + a.M33 * b.M31;
            out.M32 = a.M31 * b.M12 + a.M32 * b.M22 + a.M33 * b.M32;
            out.M33 = a.M31 * b.M13 + a.M32 * b.M23 + a.M33 * b.M33;
      }
    
  • I would forget about using pointers. Just use two dimensional arrays. Work through the multiplication in the same way you did in high school. There are examples all over the net. For example this one:

    https://codeitaway.wordpress.com/2012/01/26/c-program-to-multiply-two-matrix-multiplication-of-3x3-matrix-in-c/

  • MicrocontrolledMicrocontrolled Posts: 2,452
    edited April 11 Vote Up0Vote Down
    I've not run it but I think this would work.
    for (int i=0;i<3;i++) {
      for (int j=0;j<3;j++) {
        for (int k=0;k<3;k++) {
          resultMatrix[i][j] += firstMatrix[i][k]*secondMatrix[j][k];
        }
      }
    }
    

    Each element in the product of matrices is the sum of the products of the row and corresponding column, so this produce the output of the sum of 2 3x3 matrices. Not very efficient with 3 nested loops, though.
    Projects, tutorials, and more! http://microcontrolled.com/
Sign In or Register to comment.