MATLAB: Get all sets of cells from two arrays of cells, each of which contains exactly one cell from each column of each arrays.

cell arrays

There are two arrays of cells: A and B. They have a different size (size A is 7 by n, size B is 3 by m).
It is nessesary to form all sets of cells, each of which contains exactly one cell from each column of A and one cell from each column of B.
Thus, in each set we have n+m cells.
The total quantity of sets is: 7^n*3^m.
But how to get them?

Best Answer

  • There's no such thing as an array of cells in matlab. There are matrices or arrays (a matrix being a 2D array) and there are cell arrays (where each cell can contain another array).
    First, a helper function:
    function combs = allcomb(maxval, permlength)
    %create all permutations of length permlength of numbers from 1 to maxval
    combs = cell(1, permlength);
    [combs{:}] = ndgrid(1:maxval);
    combs = reshape(cat(permlength + 1, combs{:}), [], permlength);
    %some demo data
    A = reshape(1:14, 7, 2); %A 7 x 2 matrix
    B = reshape(1:12, 3, 4); %A 3 x 3 matrix
    rowsA = allcomb(size(A, 1), size(A, 2));
    rowsB = allcomb(size(B, 1), size(B, 2));
    colsA = repmat(1:size(A, 2), size(rowsA, 1), 1);
    colsB = repmat(1:size(B, 2), size(rowsB, 1), 1);
    indA = sub2ind(size(A), rowsA, colsA);
    indB = sub2ind(size(B), rowsB, colsB);
    [indArow, indBrow] = ndgrid(1:size(indA, 1), 1:size(indB, 1));
    C = [A(indA(indArow(:), :)), B(indB(indBrow(:), :))]
    Note that the above works with both matrices and 2D cell arrays.