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

2 ビュー (過去 30 日間)
asobrado
asobrado 2021 年 5 月 7 日
編集済み: Stephan 2021 年 5 月 10 日
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 Center および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by