Create all combination of strings

10 vues (au cours des 30 derniers jours)
Celso Mauro Nhanga Dos Santos
Commenté : per isakson le 7 Mar 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

Réponses (1)

per isakson
per isakson le 6 Mar 2021
Modifié(e) : per isakson le 7 Mar 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 commentaires
Celso Mauro Nhanga Dos Santos
Modifié(e) : Celso Mauro Nhanga Dos Santos le 6 Mar 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 le 7 Mar 2021
See my extended answer.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by