简体   繁体   中英

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

在此处输入图像描述

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM