How to get cross section of 3 dimensional array c# -
say have 3-dimensional array in c#
int space[width, height, depth];
and implement method
public int[,] getcrosssection(int position, int dimension)
where 'position' point along 'dimension' specified extract slice. important not use fact dealing 3 dimensions, in examples below fix them adding if statements , assume matrix not grow beyond 3 dimensions.
my first attempt (commented problem areas):
public int[,] getcrosssection(int position, int dimension) { int[] dimensioniterationinterval = new int[] { width, height, depth }; var dims = new list<int>(dimensioniterationinterval); dims.removeat(dimension); dimensioniterationinterval = dims.toarray(); int[,] crosssection = new int[dimensioniterationinterval[0], dimensioniterationinterval[1]]; int[] itr = new int[2]; (itr[0] = 0; itr[0] < dimensioniterationinterval[0]; itr[0]++) { (itr[1] = 0; itr[1] < dimensioniterationinterval[1]; itr[1]++) { crosssection[itr[0], itr[1]] = space[?,?,?]; //problem } } }
and second attempt, equally futile:
public int[,] getcrosssection(int position, int dimension) { int[,] dimensioniterationinterval = new int[,] { { 0, width }, { 0, height }, { 0, depth } }; dimensioniterationinterval[dimension, 0] = position; dimensioniterationinterval[dimension, 1] = position + 1; int[,] crosssection = new int[?,?]; //problem (int x = dimensioniterationinterval[0, 0]; x < dimensioniterationinterval[0, 1]; x++) { (int y = dimensioniterationinterval[1, 0]; y< dimensioniterationinterval[1, 1]; y++) { (int z = dimensioniterationinterval[2, 0]; z < dimensioniterationinterval[2, 1]; z++) { crosssection[?, ?] = space[x, y, z]; // problem } } } }
both attemps run dead ends. how solve it? it's ok have fixed iteration loops number of dimensions of space[,,]. if number of dimensions grow managable. clever/limited if statments work, not excessive ifs each dimension.
quick draft:
static int[,] getslice(int[,,] source, int dimension, int position) { int l1 = 0, l2 = 0; if (dimension == 0) { l1 = source.getlength(1); l2 = source.getlength(2); } else if (dimension == 1) { l1 = source.getlength(0); l2 = source.getlength(2); } else if (dimension == 2) { l1 = source.getlength(0); l2 = source.getlength(1); } var result = new int[l1, l2]; var s0 = dimension == 0 ? position : 0; var s1 = dimension == 1 ? position : 0; var s2 = dimension == 2 ? position : 0; var m0 = dimension == 0 ? position + 1 : source.getlength(0); var m1 = dimension == 1 ? position + 1 : source.getlength(1); var m2 = dimension == 2 ? position + 1 : source.getlength(2); (var i0 = s0; i0 < m0; i0++) (var i1 = s1; i1 < m1; i1++) (var i2 = s2; i2 < m2; i2++) { int x = 0, y = 0; if (dimension == 0) { x = i1; y = i2; } else if (dimension == 1) { x = i0; y = i2; } else if (dimension == 2) { x = i0; y = i1; } result[x, y] = source[i0, i1, i2]; } return result; }
it can generalised number of dimensions (and make code smaller , simpler).
Comments
Post a Comment