Search code examples
arraysmatlabnestedcell

Preallocate nested cell array matlab


In Matlab, I need help in preallocating nested cell array and initializing it to zeros. Problem description: I have a numeric cell array, for example, called bn. This array should be preallocatted in following way:

bn{1,1} = 0
bn{1,2}{1,1} = 0
bn{1,2}{1,2}{1,1} = 0
bn{1,2}{1,2}{1,2}{1,2} = 0

enter image description here

I also tried to describe my question with help of an image, assuming I have only three levels. Actually, I have around thirty.

Probably, with for-loop this problem can be solved . But I don't have enough imagination :-( So, please, help me experts!


Solution

  • There are some valid points raised in the comments about this likely not being the most efficient way to store your data. However, assuming there is a specific reason, you could generate this with a simple recursive function:

    bn = createNode( 1, 3 );
    
    function node = createNode( currentLayer, maxLayer )
        if currentLayer == maxLayer
            node = {0,0}; % Bottom layer is just {0,0}
        else
            % Higher layers are {0, {sub-node}}
            node = {0, createNode( currentLayer+1, maxLayer )};
        end
    end