Asked by VALERIY ZLOBIN
on 17 Jun 2019

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?

Answer by Guillaume
on 17 Jun 2019

Accepted 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);

end

Then:

%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.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Guillaume (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/467451-get-all-sets-of-cells-from-two-arrays-of-cells-each-of-which-contains-exactly-one-cell-from-each-co#comment_715493

## VALERIY ZLOBIN (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/467451-get-all-sets-of-cells-from-two-arrays-of-cells-each-of-which-contains-exactly-one-cell-from-each-co#comment_715536

Sign in to comment.