# How to implement recurrence operations efficiently?

This question is related to this one. I basically want to partition a volume recursively.

Consider a volume as

vol = ExampleData[{"TestImage3D", "MRbrain"}];

Now,

temp = vol;

If I do this,

{w, d, h} = ImageDimensions[temp];
partition1 =
ImagePartition[temp, {Floor[w/2], Floor[d/2], Floor[h/2]}];
reconstruction1 =
ImageAssemble[partition1 /. i_Image3D :> ImagePad[i, 5, 0]]

This gives me first level of partitions.

If I do the following

{w, d, h} = ImageDimensions[temp];
partition1 =
ImagePartition[temp, {Floor[w/2], Floor[d/2], Floor[h/2]}];
selection1 = partition1[[1, 1, 2]];
partition2 =
ImagePartition[selection1, {Floor[w/4], Floor[d/4], Floor[h/4]}];
reconstruction2 =
ImageAssemble[partition2 /. i_Image3D :> ImagePad[i, 5, 0]];
partition1[[1, 1, 2]] =
ImageResize[reconstruction2, {Floor[w/2], Floor[d/2], Floor[h/2]}];
reconstruction1 =
ImageAssemble[partition1 /. i_Image3D :> ImagePad[i, 5, 0]]

I get second level splitting.

{w, d, h} = ImageDimensions[temp];
partition1 =
ImagePartition[temp, {Floor[w/2], Floor[d/2], Floor[h/2]}];
selection1 = partition1[[1, 1, 2]];
partition2 =
ImagePartition[selection1, {Floor[w/4], Floor[d/4], Floor[h/4]}];
selection2 = partition2[[1, 1, 2]];
partition3 =
ImagePartition[selection2, {Floor[w/8], Floor[d/8], Floor[h/8]}];
reconstruction3 =
ImageAssemble[partition3 /. i_Image3D :> ImagePad[i, 5, 0]];
partition2[[1, 1, 2]] =
ImageResize[reconstruction3, {Floor[w/4], Floor[d/4], Floor[h/4]}];
reconstruction2 =
ImageAssemble[partition2 /. i_Image3D :> ImagePad[i, 5, 0]];
partition1[[1, 1, 2]] =
ImageResize[reconstruction2, {Floor[w/2], Floor[d/2], Floor[h/2]}];
reconstruction1 =
ImageAssemble[partition1 /. i_Image3D :> ImagePad[i, 5, 0]]

And the above code snippet gives me third level splitting.

How can I make this process iterative in an efficient way so that I can set the level as a parameter and get the final result after how many iterations I wish?

You could to that by defining a function that splits a single image into 8 ones, make it Listable.

ClearAll[splitImage];
SetAttributes[splitImage, Listable]
splitImage[temp_Image3D] :=
Map[