Create all combination of strings

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

回答(1 个)

per isakson
per isakson 2021-3-6
编辑:per isakson 2021-3-7
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 个评论
Celso Mauro Nhanga Dos Santos
编辑:Celso Mauro Nhanga Dos Santos 2021-3-6
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by