Question

I need to create a 4x4 matrix class for a 3D engine in C#. I have seen some other engines storing the matrix values in single float member variables / fields like this:

float m11, m12, m13, m14
float m21, m22, m23, m24
float m31, m32, m33, m34
float m41, m42, m43, m44

However, I thought storing them in a two dimensional array would be more useful for transformations / calculations with the matrices:

float[4][4];

I also thought of a one dimensional array - but it looks less self explanatory and wouldn't give me an advantage over the first option:

float[16];

In C++, I always used the "union" keyword to have all of the above storing possibilites at once. However, C# does not seem to have this keyword, so I have to decide which one I want to use.

What is the fastest way of storing the 4x4 matrix when applying transformations etc.? Which option would you choose when thinking about usability?

Was it helpful?

Solution

You could use a two dimensional array:

float[,] matrix = new float[4,4];

This is different than a jagged array:

float[][] matrix = new float[][4];

A two dimensional array is, underneath, stored as one big one dimensional array. The class simply abstracts that away from you and provides accessors that provide two (or more) dimensions. Because it is stored as a one dimensional array in the back end you will maintain cache/memory locallity.

OTHER TIPS

Why don't you have a look on this CodeProject.com article, Efficient Matrix Programming in C#.

You can also have a look at Declaring an Array (Visual C#) for wide variety of option for defining your own Matrix Data Structure.

the fastest way is using pointers along with the unsafe key word. But, this, as the keyword indicates, is unsafe.

for more information about pointers in C# look at this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top