Home > C++ Classes, Programming > Matrix Class

Matrix Class

August 1st, 2009 Leave a comment Go to comments

To download (lightweight, no support for matrix inverse or determinant):

1
bzr branch http://bazaar.enseed.com/demo/matrix/

To download (full version with matrix inverse and determinant):

1
bzr branch http://bazaar.enseed.com/demo/matrix-with-inverse/

This is a c++ matrix class designed to minimize errors at runtime and allow the compiler to optimize as much as possible. The class uses three template arguments:

  • The data type used (i.e. float or double)
  • The matrix width (nb of columns)
  • The matrix height (nb of columns)
1
2
template
class Matrix { ... };

I have seen several implementations of matrices in C++ where the size of the matrix is given as a parameter to the constructor and the storage is build dynamically. Here, having the width and height as template parameters has several advantages over the tradition dynamic matrix class:

  • The compiler knows how many elements you have in your matrix and can unroll and optimize loops
  • You can ensure that you are not doing operations on matrices with incompatible sizes (multiplcation for example). The compiler will tell you at compile time if you do.
  • When you receive a matrix as a function parameter, you don’t need to check that it is what you expect it to be. For example, if your function expects a 4×4 matrix, you’ll ask for a Matrix and you are guaranteed to get what you asked for.

There are a few typedefs at the bottom for convenience:

1
2
3
4
5
6
7
8
typedef Matrix Matrix1f;
typedef Matrix Matrix2f;
typedef Matrix Matrix3f;
typedef Matrix Matrix4f;
typedef Matrix Matrix1d;
typedef Matrix Matrix2d;
typedef Matrix Matrix3d;
typedef Matrix Matrix4d;

So you can use Matrix4d instead of Matrix

For the rest, just have a look at the header file to see what’s available. In short, you can do things like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
static double m[9] = {
1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0
};

Matrix3d m3d = Matrix3d(m);

m3d[0][1] = 0;

m3d += Matrix3d::identityMatrix();

m3d.transpose();

m3d = m3d * Matrix4d::identityMatrix(); // ERROR: the compiler will complain
Categories: C++ Classes, Programming Tags:
  1. No comments yet.
  1. No trackbacks yet.
*

Please leave these two fields as-is:

Protected by Invisible Defender. Showed 403 to 158,454 bad guys.