simple matrix routines

R

Rohan Shah

i am looking for some simple matrix routines: vector*matrix,
matrix*matrix etc...in the form of code like the following that
multiplies two vectors:

void vmult(double* aa, double* bb, double* cc, int lnt) {
//cc += lnt;
while(lnt--) {
*cc++ = *bb++ * *aa++;
}
}

thanks in advance - Rohan
comp.lang.c
 
P

Pete C.

Rohan said:
i am looking for some simple matrix routines: vector*matrix,
matrix*matrix etc...in the form of code like the following that
multiplies two vectors:

void vmult(double* aa, double* bb, double* cc, int lnt) {
//cc += lnt;
while(lnt--) {
*cc++ = *bb++ * *aa++;
}
}

thanks in advance - Rohan
comp.lang.c

C++ not C, but very easy to convert:

struct vector4
{
float val[4];

float& operator[] (uint i) {return val;}
float& x() {return val[0];}
float& y() {return val[1];}
float& z() {return val[2];}
float& w() {return val[3];}

vector4()
{x()=0.0f;y()=0.0f;z()=0.0f;w()=1.0f;}
vector4(float X,float Y,float Z,float W)
{x()=X;y()=Y;z()=Z;w()=W;}
};

struct matrix4x4
{
float val[4][4];
float* operator[] (uint i) {return val;}
};

matrix4x4 BuildIdentityMatrix()
{
matrix4x4 out;
for(uint i=0;i<4;++i)
{
for(uint j=0;j<4;++j)
{
if(i==j)
out[j] = 1.0f;
else
out[j] = 0.0f;
}
}
return out;
}

matrix4x4 BuildTranslationMatrix(vector4 t)
{
vector4 tn = VectorNormalize(t);
matrix4x4 out = BuildIdentityMatrix();
out[3][0] = tn.x();
out[3][1] = tn.y();
out[3][2] = tn.z();
return out;
}

matrix4x4 MatrixMult(matrix4x4 a, matrix4x4 b)
{
matrix4x4 result;
for(uint i=0;i<4;++i)
{
for(uint j=0;j<4;++j)
{
float value = 0.0f;
for(uint k=0;k<4;++k)
{
value = value + a[k] * b[k][j];
}
result[j] = value;
}
}
return result;
}

vector4 MatrixApply(matrix4x4 m, vector4 v)
{
vector4 result;
for(uint i=0;i<4;++i)
{
float value = 0.0f;
for(uint j=0;j<4;++j)
{
value = value + v[j] * m[j];
}
result = value;
}
return VectorNormalize(result);
}

vector4 VectorNormalize(vector4 v)
{
vector4 out;
out[0] = v[0] / v[3];
out[1] = v[1] / v[3];
out[2] = v[2] / v[3];
out[3] = 1.0f;
return out;
}

float DotProduct(vector4 v1, vector4 v2)
{
return v1.x()*v2.x() + v1.y()*v2.y() + v1.z()*v2.z();
}

vector4 CrossProduct(vector4 v1, vector4 v2)
{
return vector4(v1.y()*v2.z()-v1.z()*v2.y(), v1.z()*v2.x()-v1.x()*v2.z(),
v1.x()*v2.y()-v1.y()*v2.x(), 1.0f);
}

- Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top