How to obtain all permutations of multiple cell arrays?

6 views (last 30 days)
I have a few cell arrays of character vectors - let's say 3 in this case - A, B, C.
A={'a1'; 'a2'; 'a3'};
B={'b1'; 'b2'};
C={'c1'; 'c2'; 'c3'; 'c4'};
I wish to find all permutations of elements of A, B, and C. That is, one element from each. Such as:
{'a1', 'b1', 'c1'; 'a1', 'c1', 'b1'; 'b1', 'a1', 'c1'; 'a1', 'b1', 'c2'; .... }
Please note that I am not looking for only combinations - I believe that would have been easily addressed by:
X=combinations(A, B, C);
I am also not looking for permutations that would produce combinations/permutations of elements from within one of the cell arrays above - so that I couldn't just do:
X=vertcat(A,B,C);
perms(X);
Is there an efficient way to do this without all sorts of loops?

Accepted Answer

Matt J
Matt J on 17 Mar 2024
Edited: Matt J on 17 Mar 2024
This is better because the for loop is only 6 iterations long.
A={'a1'; 'a2'; 'a3'};
B={'b1'; 'b2'};
C={'c1'; 'c2'; 'c3'; 'c4'};
p=perms(1:3);
c= combinations(C,B,A);
N=height(p)
N = 6
Z=cell(N,1);
for i=1:N
Z{i}=c(:,p(i,:));
end
Z=vertcat(Z{:})
Z = 144x3 table
A B C ______ ______ ______ {'a1'} {'b1'} {'c1'} {'a2'} {'b1'} {'c1'} {'a3'} {'b1'} {'c1'} {'a1'} {'b2'} {'c1'} {'a2'} {'b2'} {'c1'} {'a3'} {'b2'} {'c1'} {'a1'} {'b1'} {'c2'} {'a2'} {'b1'} {'c2'} {'a3'} {'b1'} {'c2'} {'a1'} {'b2'} {'c2'} {'a2'} {'b2'} {'c2'} {'a3'} {'b2'} {'c2'} {'a1'} {'b1'} {'c3'} {'a2'} {'b1'} {'c3'} {'a3'} {'b1'} {'c3'} {'a1'} {'b2'} {'c3'}

More Answers (2)

AR
AR on 12 Mar 2024
Moved: Voss on 16 Mar 2024
I suppose I could do:
Z = combinations(A, B, C);
for i=1:size(Z,1)
Y{i,1} = perms(Z{i, :});
end
X = vertcat(Y{:});
I'm just wondering if there's a better way to do it, or if anyone can spot a reason why the above might fail (typically some dimension mismatch).

Matt J
Matt J on 17 Mar 2024
Edited: Matt J on 17 Mar 2024
Using this FEX download,
c= table2cell(combinations(C,B,A));
result = blkColon( c(:,perms(1:3)') , [1,3])
result =
144×3 cell array
{'a1'} {'b1'} {'c1'}
{'a2'} {'b1'} {'c1'}
{'a3'} {'b1'} {'c1'}
{'a1'} {'b2'} {'c1'}
{'a2'} {'b2'} {'c1'}
{'a3'} {'b2'} {'c1'}
{'a1'} {'b1'} {'c2'}
{'a2'} {'b1'} {'c2'}
{'a3'} {'b1'} {'c2'}
{'a1'} {'b2'} {'c2'}
{'a2'} {'b2'} {'c2'}
{'a3'} {'b2'} {'c2'}
{'a1'} {'b1'} {'c3'}
...

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!