Spot The Bug!

Lately I have been tinkering with a simple little 3D graphics program in my spare time. To support my various graphics and math projects I have put together a simple C++ math library including matrices, vectors, and the like. My matrices are stored in row-major order, like most matrices in C/C++ programs, but OpenGL uses column-major order. “Simple,” I think, “I just need to transpose my orientation matrices before passing them to OpenGL!”

But it just wouldn’t work. See if you can figure out why:

  template<class T, int dim> class SquareMatrix {
    ...
    /** Transpose the matrix. **/
    void transpose() {
      for (int r = 0; r < dim; r++) {
        for (int c = 0; c < dim; c++) {
          // Diagonal elements don't need transposing!
          if (r == c) continue;

          T tmp = getElem(r, c);
          setElem(r, c, getElem(c, r));
          setElem(c, r, tmp);
        }
      }
    }
    ...
  };

3 Responses to “Spot The Bug!”

  1. Chris B Says:

    Just rename the function “transposetranspose” and keep it around for when you want to transpose something twice. :)

  2. donnie Says:

    Very good Chris, I’m impressed!

    You can imagine my embarrassment when I discovered the problem…

    Here is the updated version:

        /** Transpose the matrix. **/
        void transpose() {
          for (int r = 0; r < dim; r++) {
            for (int c = r + 1; c < dim; c++) {
              T tmp = getElem(r, c);
              setElem(r, c, getElem(c, r));
              setElem(c, r, tmp);
            }
          }
        }
    
  3. Abhishek Says:

    Hi Donnie,

    The above code chunk transposes each element twice and hence u getting the same matrix finally. The approach should be go for either upper trianular elements or lower ones for transposing.

    Also, this will give you better preformance numbers from square(n) to n*(n-1)/2 :))

    Hope u remember me ..

    +Abhishek

Leave a Reply