MATLAB: Change dimensions of a cell depending on the number of inputs

cell arraysvariable inputs

I am building a model with nodes made of different number of states. Each node is defined as a cell containing the probability of each state to happen. For example, the node A has 2 states and node B has 3 states, so they are represented as 1×2 and 1×3 cells, i.e.,
A = cell(1,2);
B = cell(1,3);
There is a third cell C that is a child node of A and B (i.e., probabilities of C are conditioned to those of A and B, the "parent nodes") that has 4 states. So, this will be a 2x3x4 cell, as follows:
C = cell(2,3,4);
Is there a Matlab function or a way to create automatically the cell C with dimensions that depend on the number of the parents and that each of the dimensions correspond to the length of each of the parents of C? Basically, I want a program that put those numbers "2", "3" and "4" in the argument of the cell C automatically depending on the length of the parents and C.
An extra example to clarify. Suppose I have extra 2 nodes D and E with 2 and 6 states (D = cell(1,2); and E = cell(1,6);). So, I want that the program creates a new cell C whose dimensions are cretated automatically from its parent nodes, so the program should fill up the argument of the cell C as follows:
C = cell(2,3,2,6,4);
Note that the number of states of the node C has to be at the end of the argument.
Thanks for your help guys!

Best Answer

  • I'm assuming that your cells will not be individual variables (impossible to work with) but stored for example in another cell array:
    function childcell = makecell(parents, numstates)
    %creates a child cell of the correct size based on the size of the parents
    %parents: a cell array of N cell arrays of arbitrary size.
    %numstates: number of states of the child
    %child cell: the child of size numel(parents{1}) x numel(parents{2}) x ... x numel(parents{N}) x numstates
    validateattributes(parents, {'cell'}, {});
    validateattributes(numstates, {'numeric'}, {'integer', 'scalar', 'positive'})
    parentsizes = cellfun(@numel, parents, 'UniformOutput', false);
    childcell = cell(parentsizes{:}, numstates);