# Matrix Math

Since I was able to get excellent help ealier in less that a half an hour I figure I’ll post another question This ones a bit longer, I’ve tried to provided only the code that is required:

Can somebody please explain to me whats wrong here?
And I know its not the DEG_TO_RAD stuff, the equation is right, and I tried it without it too.

/////////////////////////////////////////////////////////////////////
#include <math.h>

typedef GLfloat zfloat;
typedef GLint zint;
/////////////////////////////////////////////////////////////////////
// Matrix structure
//
class ZMatrix
{
public:
zfloat m[16];

``````    // Constructor
ZMatrix()

// Allow array-like interface to OpenGL's backwards matrices
inline zfloat&At(zint row, zint col)
{ return (m[col * 4 + row ]); }

{ m[0] = m[5] = m[10] = m[15] = 1.0;
m[1] = m[2] = m[3] =
m[4] = m[6] = m[7] =
m[8] = m[9] = m[11] =
m[12] = m[13] = m[14] = 0.0; }

inline RotateX(zfloat x)
{
At(2,2) = At(3,3) = cos( Z_DEG_TO_RAD(x) );
}

inline glMultMatrix()
{ glMultMatrixf( m ); }
``````

};
//
/////////////////////////////////////////////////////////////////////

``````zfloat xoff = (offset controlled by keypresses);
zfloat yaw = (angle controlled by keypresses);
``````

In my render loop I had:

``````glPushMatrix();
glTranslatef( 0.0, 0.0, xoff );
glRotatef( yaw, 0.0, 1.0, 0.0 );
glTranslatef( -4096.0, -768.0, 4596.0 );
glRotatef( -90.0, 1.0, 0.0, 0.0 );
``````

Which kinda sorta worked… at least well enough for me to see and move around. If I replace the above with:

``````glPushMatrix();
glTranslatef( 0.0, 0.0, xoff );
glRotatef( yaw, 0.0, 1.0, 0.0 );
glTranslatef( -4096.0, -768.0, 4596.0 );
ZMatrix mat;
mat.RotateX( -90.0 );
mat.glMultMatrix();
``````

Everything goes berserk!

Yepp, a locical error…

The error is in you function At(row, col). Remember that the first row (aswell as first column too) in you matrix is 0 (zero), and not 1 (one). So by doing At(2,2)=cos(x) means you set third row in the third column to cos(x), when you intend to set second row in second column. Just have a look at how it works, if you pass At(3,3), it will return the address to m[3*4 + 3], which equals m[15], which in turn is the last (row 4, col 4) cell in your matrix. Either change all At()-calls by decreasing all arguments by one, or change the function to automativcally decrease row and col by one before returning the address.

Doh!! Thank you very much, I should have been able to figure that one out