By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,289 Members | 1,277 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,289 IT Pros & Developers. It's quick & easy.

simple matrix routines

P: n/a
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
Nov 14 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Rohan Shah wrote:
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[i];}
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[i];}
};

matrix4x4 BuildIdentityMatrix()
{
matrix4x4 out;
for(uint i=0;i<4;++i)
{
for(uint j=0;j<4;++j)
{
if(i==j)
out[i][j] = 1.0f;
else
out[i][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[i][k] * b[k][j];
}
result[i][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][i];
}
result[i] = 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
Nov 14 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.