How to find every combination of values in a cell array?
2 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Stephan
on 7 May 2021
Edited: Stephan
on 10 May 2021
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
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!