Question

I wrote a small 3D matrix creation class for my project. It goes like this.

class _3DMatrix
    {
        public static int[, ,] m = new int[3, 3, 3];

        public _3DMatrix(int a)
        {
            for (int x = 0; x < 3; x++)
            {
                for (int y = 0; y < 3; y++)
                {
                    for (int z = 0; z < 3; z++)
                    {
                        m[x, y, z] = a;
                    }
                }
            }
        }

Now it seems that I have to create a NxNxN matrix that would take the N values as constructor parameters. What would be the easiest way to do it? Any tips/code snippets would help immensely. Thanks.

Was it helpful?

Solution

Replace your constant 3 by a variable:

Please note that I changed the array to be non-static because having a static array does not make sense here.

class _3DMatrix
{
    public int[, ,] m;

    public _3DMatrix(int size, int a)
    {
        m = new int[size, size, size];

        for (int x = 0; x < size; x++)
        {
            for (int y = 0; y < size; y++)
            {
                for (int z = 0; z < size; z++)
                {
                    m[x, y, z] = a;
                }
            }
        }
    }

OTHER TIPS

You can define the size of your matrix m in the constructor. As long as you do not change dimensionality, this will be fine:

EDIT: Note that I have used three separate sizes for your matrix (n1, n2, n3) but there's no reason you couldn't simply use 1 size parameter (n) if you never wanted matrices of different sizes.

class _3DMatrix
{
    public static int[, ,] m;

    public _3DMatrix(int a, int n1, int n2, int n3)
    {
        m = new int[n1,n2,n3];
        for (int x = 0; x < n1; x++)
        {
            for (int y = 0; y < n2; y++)
            {
                for (int z = 0; z < n3; z++)
                {
                    m[x, y, z] = a;
                }
            }
        }
    }

Your code (as well as all the answers ) create a NxN matrix that all the elements have the same value a. If this is your objective, you are fine. If not you have to pass in the creation function the matrix elements:

class _3DMatrix
{
    public int[, ,] m;

    public _3DMatrix(int size, int[,,] a)
    {
        m = new int[size, size, size];

        for (int x = 0; x < size; x++)
        {
            for (int y = 0; y < size; y++)
            {
                for (int z = 0; z < size; z++)
                {
                    m[x, y, z] = a[x,y,z];
                }
            }
        }
    }

Shorter way to do it:

class _3DMatrix
{
    public int[, ,] m;

    public _3DMatrix(int N, int a)
    {
        m = new int[N, N, N];
        Buffer.BlockCopy(Enumerable.Repeat(a, m.Length).ToArray(), 0, m, 0, m.Length * Marshal.SizeOf(a));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top