Create all combination of strings

6 visualizaciones (últimos 30 días)
Celso Mauro Nhanga Dos Santos
Celso Mauro Nhanga Dos Santos el 6 de Mzo. de 2021
Comentada: per isakson el 7 de Mzo. de 2021
Hello guys,
I need to create a matrix permutation with value from P1:P8. I tried to use the following code:
Pat = sym('p', [1 8]);
pn = nchoosek([Pat],5);
Str = string(pn)
"p1" "p2" "p3" "p4" "p5"
"p1" "p2" "p3" "p4" "p6"
"p1" "p2" "p3" "p5" "p6"
"p1" "p2" "p4" "p5" "p6"
"p1" "p3" "p4" "p5" "p6"
"p2" "p3" "p4" "p5" "p6"
"p1" "p2" "p3" "p4" "p7" ...
The code worked; nevertheles, it gave me only all possible combinations instead of all permutations. Next I tried this following code:
x = sym('p', [1 8]);
K = 5;
C = cell(K, 1);
[C{:}] = ndgrid(x);
y = cellfun(@(x){x(:)}, C);
y = [y{:}];
But the thing is that this code seems a lot for my computer to handle. So would like your help to see if I can generate all permitation of the string P1:P8.
Thank you in advance

Respuestas (1)

per isakson
per isakson el 6 de Mzo. de 2021
Editada: per isakson el 7 de Mzo. de 2021
In response to comment
Does the function, cssm(), do what you ask for?
>> all_permutations = cssm( 3, 2 )
all_permutations =
6×2 string array
"p2" "p1"
"p1" "p2"
"p3" "p1"
"p1" "p3"
"p3" "p2"
"p2" "p3"
>>
where
function all_permutations = cssm( n, k )
str = arrayfun( @(jj) "p"+jj, (1:n) );
% or shorter str="p"+(1:n);
all_combinations = nchoosek( str, k );
%
ix = 1;
fac = factorial( k );
all_permutations = strings( size(all_combinations,1)*fac, k );
for combination = permute( all_combinations, [2,1] )
all_permutations( 1+(ix-1)*fac : ix*fac, : ) = perms( combination );
ix = ix + 1;
end
%
test = unique( all_permutations, 'rows' );
assert( all( size(test) == size(all_permutations) ) );
end
  2 comentarios
Celso Mauro Nhanga Dos Santos
Celso Mauro Nhanga Dos Santos el 6 de Mzo. de 2021
Editada: Celso Mauro Nhanga Dos Santos el 6 de Mzo. de 2021
I am getting a response with numerical value only. So since I’m using non-numerical value, it’s showing an error.
Thanks for your response.
per isakson
per isakson el 7 de Mzo. de 2021
See my extended answer.

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by