How to find every combination of values in a cell array?

2 次查看(过去 30 天)
Hi, I have a cell array with a variable number of values inside each cell, something like this:
M=
{1,2,3} {4,5,6}{7,8,9}
{10,11}{12,13}{14,15}
{16,17,18,19,20}{21,22,23,24}{25,26,27,28}
I want to create every possible combination of cell arrays contanining one value of each cell, something like this:
m1= m2= m3= m4=
{1}{4}{7} | {2}{4}{7} | {3}{4}{7} | {1}{5}{7}
{10}{12}{14} | {10}{12}{14} | {10}{12}{14} | {10}{12}{14}
{16}{21}{25} | {16}{21}{25} | {16}{21}{25} | {16}{21}{25}
---
and so on.
Is it possible to do it? Tried with nchoosek and cell2mat, but the vary in length of array is a problem I couldn't resolve.

采纳的回答

Stephan
Stephan 2021-5-7
编辑:Stephan 2021-5-10
One way, using allcomb:
M = {[1,2,3], [4,5,6],[7,8,9];
[10,11],[12,13],[14,15];
[16,17,18,19,20],[21,22,23,24],[25,26,27,28]};
res = {allcomb(M{1,1:3}, M{2,1:3}, M{3,1:3})};
res = permute(reshape(res{:}',3,3,[]),[2 1 3]);
The order of the results is a bit different then you wanted, but always only one value is changed:
>> res(:,:,1:5)
ans(:,:,1) =
1 4 7
10 12 14
16 21 25
ans(:,:,2) =
1 4 7
10 12 14
16 21 26
ans(:,:,3) =
1 4 7
10 12 14
16 21 27
ans(:,:,4) =
1 4 7
10 12 14
16 21 28
ans(:,:,5) =
1 4 7
10 12 14
16 22 25
  1 个评论
asobrado
asobrado 2021-5-7
Works perfect! It's quite a pity Matlab can't handle the size of the real cell array I am using, but the solution is very straightforward. Thank you.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by