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

2 vues (au cours des 30 derniers jours)
asobrado
asobrado le 7 Mai 2021
Modifié(e) : Stephan le 10 Mai 2021
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.

Réponse acceptée

Stephan
Stephan le 7 Mai 2021
Modifié(e) : Stephan le 10 Mai 2021
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 commentaire
asobrado
asobrado le 7 Mai 2021
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by