How to obtain all permutations of multiple cell arrays?

6 visualizaciones (últimos 30 días)
AR
AR el 12 de Mzo. de 2024
Editada: Matt J el 17 de Mzo. de 2024
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?

Respuesta aceptada

Matt J
Matt J el 17 de Mzo. de 2024
Editada: Matt J el 17 de Mzo. de 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'}

Más respuestas (2)

AR
AR el 12 de Mzo. de 2024
Movida: Voss el 16 de Mzo. de 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 el 17 de Mzo. de 2024
Editada: Matt J el 17 de Mzo. de 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'}
...

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by