4
$\begingroup$

I would like to generate a 3D Grid, not for displaying, but to do computations on it, so no draw functions I guess.

I have a simple version of what I am thinking, however, it is terribly slow:

generateMesh[size_, width_, distance_] := 
 Image3D@ParallelTable[
     If[#1 && #2 || #1 && #3 || #2 && #3, 1, 0] & @@ 
         (MemberQ[Range[0, width - 1], Mod[#, distance]] & /@ 
              {x, y, z}), 
     {x, 0, size}, {y, 0, size}, {z, 0, size}]

The Image3D is only to see if it is correct and not part of the speed issue. Even a call to e.g. generateMesh[200, 2, 20] takes about 30s or more on a laptop. This seems quite a lot for such a simple task.

Does anyone know

  1. a way to improve performance?
  2. know if the above code contains any typical don'ts of Mathematica programming? I guess I am evaluating things over and over again, because I am not evaluating the function passed to Table, but I do not know how to avoid this.
$\endgroup$
6
$\begingroup$

The following is very fast:

gm2[size_, width_, distance_] :=
 Module[{f, bc = BooleanCountingFunction[{2, 3}, 3]},
  f = Join[ConstantArray[True, width], ConstantArray[False, distance - width]];
  ArrayPad[Boole@Outer[bc, f, f, f], {0, size - distance + 1}, "Periodic"]]

Timing[gm2[200, 2, 20];]
(* {0.234375, Null} *)

Image3D@gm2[20, 2, 5]

Mathematica graphics

It is so fast, you can even Manipulate it:

Manipulate[
 Image3D@gm2[size, width, distance],
 {size, 20, 200, 1}, {width, 1, 10, 1}, {distance, 10, 20, 1}]

Mathematica graphics


Previous (slower) This one gives you a boost of at least x3

gm1[size_, width_, distance_] := 
 Module[{f, bc = BooleanCountingFunction[{2, 3}, 3]}, 
  f = Flatten[ Array[Join[ConstantArray[True, width], 
                          ConstantArray[False, distance - width]] &, 
                    IntegerPart[size/distance] + 1]][[;; size + 1]];
  Boole@Outer[bc, f, f, f]]

Image3D@gm1[50, 2, 20]

Mathematica graphics

$\endgroup$
  • 1
    $\begingroup$ With my computer it's boost x 16 $\endgroup$ – eldo Dec 11 '15 at 17:26
  • $\begingroup$ @eldo Thanks! Good to know :) $\endgroup$ – Dr. belisarius Dec 11 '15 at 17:54
  • $\begingroup$ @eldo could you check the new version? $\endgroup$ – Dr. belisarius Dec 12 '15 at 22:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.