How to obtain all permutations of multiple cell arrays?

6 次查看(过去 30 天)
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?

采纳的回答

Matt J
Matt J 2024-3-17
编辑:Matt J 2024-3-17
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'}

更多回答(2 个)

AR
AR 2024-3-12
移动:Voss 2024-3-16
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 2024-3-17
编辑:Matt J 2024-3-17
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'}
...

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by