Tuesday, July 14, 2009

How do I create a sparse 3D matrix in C++?

I need to create a matrix of size (256, 256, 256) on which I can perform some mathematical operations. Usually I have been using Boost uBLAS for matrix math, but I don't think I can create a 3D matrix there. I tried using an int Array[256][256][256] but this was way too large and I experienced a stack overflow.

How do I create a sparse 3D matrix in C++?
Well, it is easier than you think. You have to allocate memory, either statically or dynamically on the heap to hold the variable. It is far too big for use as an auto allocation at 256*256*256*(sizeof [variable type]); or about


16,777,216*4 bytes at a minimum, over 64 MB of RAM. A better idea than a matrix may be to keep only boundary or center point coordinate triples in memory and assume that they are on an empty grid. This way a sphere can be defined as an object with a radius r and a center point triple (x,y,z). A box becomes a set of two ordered triples, (x,y,z) that represents the two opposite corners in three space. This will save quite a bit of space.


If a matrix is still required, then you need to allocate as small a matrix as possible and allocate and deallocate memory for the variable arrays at appropriate points in the program. In C++, this can be done most efficiently with the keywords new and delete. I hope that this helps you out. Below are a couple of good forum sites with tutorials and articles.


No comments:

Post a Comment