Here's some vector math functions I used in an OpenGL program a while back. They are pretty self explanatory. I would start with vectors before you do matrices.
void vectorCopy(float dest[3], float src[3]) // vector copy
{
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
}
void vectorScale(float dest[3], float v[3], float s) // vector times scalar
{
dest[0] = v[0]*s;
dest[1] = v[1]*s;
dest[2] = v[2]*s;
}
void vectorAdd(float dst[3], float srcA[3], float srcB[3]) // vector add
{
dst[0] = srcA[0] + srcB[0];
dst[1] = srcA[1] + srcB[1];
dst[2] = srcA[2] + srcB[2];
}
void vectorSubtract(float dst[3], float srcA[3], float srcB[3]) // vector subtract
{
dst[0] = srcA[0] - srcB[0];
dst[1] = srcA[1] - srcB[1];
dst[2] = srcA[2] - srcB[2];
}
float getLength(float A[3]) // magnitude of vector
{
return sqrt( (A[0]*A[0])+(A[1]*A[1])+(A
}
void normalize (float vec[3]) // Normalize vector
{
const float squaredLen = vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2];
const float invLen = 1.f / (float) sqrt (squaredLen);
vec[0] *= invLen; vec[1] *= invLen; vec[2] *= invLen;
}
float dot(float A[3], float B[3]) // dot product
{
return ( A[0]*B[0] + A[1]*B[1] + A[2]*B[2]);
}
Main Topics
Browse All Topics





by: Fippy_DarkpawPosted on 2004-06-08 at 13:12:48ID: 11263850
If you were on Windows I would suggest just using the DirectX math libraries. It has all vector and matrix operations built in.
Use OpenGL for the plotting, nice cross-platform solution. There are REALLY good openGL tutorials at nehe.gamedev.net
If you want to implement the matrices yourself they arent too hard. Just make a class Matrix that holds some 2D arrays. For example,
class Matrix
{
float matrix[rows][columns];
Matrix add();
Matrix multiply();
Matrix transpose(); etc....
}
Then build in addition, subtraction, multiplication, transpose etc....
Here's some algorithms:
Algorithm #1 – Matrix Addition
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
A[i][j] = B[i][j] + C[i][j];
Algorithm #2 – Matrix Multiplication
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
for (k = A[i][j] = 0; k < n; k++)
A[i][j] += B[i][k] * C[k][j];
Algorithm #3 – Matrix Transposition
for (i = 0; i < n-1; i++)
for (j = i+1; j < n; j++){
temp = A[i][j];
A[i][j] = A[j][i];
A[j][i] = temp;
}